leetcode20. 有效的括号

问题连接:20. 有效的括号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class  {

*
* 这道题完美契合栈的所有特点,使用栈可以直接匹配解决
*
* @param s
* @return
*/
public static boolean isValid(String s) {
Stack<Character> stack = new Stack();
char[] chars = s.toCharArray();
for (char c: chars) {
if (stack.size() > 0) {
if (c == '}' && stack.peek() == '{') {
stack.pop();
continue;
}
if (c == ']' && stack.peek() == '[') {
stack.pop();
continue;
}
if (c == ')' && stack.peek() == '(') {
stack.pop();
continue;
}
}
stack.push(c);
}
return stack.size() == 0 ? true : false;
}
}