改进版的有效括号算法(堆栈)

添加更多的括号

示例

1
2
3
4
5
6
7
//(){}[]
(] //error
() //ok
[] //ok
{} //ok
[()] //ok
[{}) //error

Stack=> FILO
左半括号加入栈中, 右半括号与栈顶字符串拼接后比较是否可以组成一个完整的括号

算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean validParentheses(String s) {
Stack<String> stack = new Stack<>();
char[] chars = s.toCharArray();
for (char c : chars) {
String str = String.valueOf(c);
if (Arrays.asList("(", "[", "{").contains(str)) {
stack.push(String.valueOf(c));
} else if (Arrays.asList(")", "]", "}").contains(str)) {
if (stack.size() == 0 || !Arrays.asList("()", "[]", "{}").contains(stack.lastElement() + str)) {
return false;
}
stack.pop();
}
}
return stack.size() == 0;
}