leetcode-20-java

问题:20. Valid Parentheses

1
2
3
4
5
6
7
8
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

leetcode地址

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
32
33
34
35
36
    public static boolean isValid(String s) {
if ("".equals(s)) {
return true;
}
if (s.length()%2 != 0) {
return false;
}
Stack<Character> stack = new Stack<>();
char[] chars = s.toCharArray();
for (char c : chars) {
if (stack.isEmpty()) {
stack.push(c);
continue;
}

if (isMath(stack.peek(), c)) {
stack.pop();
} else {
stack.push(c);
}
}

return stack.isEmpty();
}

private static boolean isMath(char c1, char c2) {
// if (c1 == '(') {
// return c2 == ')';
// } else if (c1 == '[') {
// return c2 == ']';
// } else if (c1 == '{') {
// return c2 == '}';
// }
int sum = c1 + c2;
return sum == 81 || sum == 184 || sum == 248;
}

一些IDE编辑器的语法校验也是通过压栈、弹栈的方式判定括号是否合法