您的位置:首页 > 其它

leetcode解题方案--020--Valid Parentheses

2017-10-23 18:30 417 查看

题目

检查括号合法性

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

分析

设置一个栈,遇到左括号入栈,遇到右括号和栈顶元素比较,一致就出栈,结束时查看栈是否为空

public static boolean isValid(String s) {
Stack<Character> aa = new Stack<>();
char [] ss = s.toCharArray();
for (int i = 0; i<ss.length;i++) {
switch (ss[i]) {
case '{':
aa.push('}');
break;
case '[':
aa.push(']');
break;
case '(':
aa.push(')');
break;
default:
if (aa.empty()) return false;
char xxx = aa.peek();
if (xxx!=ss[i]) {
return false;
} else {
aa.pop();
}
}
}
return aa.empty();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: