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.
package cn.edu.csu;
import java.util.ArrayDeque;
import java.util.Deque;
public class ValidParenthesesSolution {
//栈可以记住顺序,是解决匹配问题的首选,这里使用Deque的典型实现ArraryDeque来实现栈
public boolean isValid(String s) {
int len = s.length();
if (len % 2 != 0) {
return false;
}
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < len; i++) {
switch (s.charAt(i)) {
case ')':
if (!stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else {
stack.push(s.charAt(i));
}
break;
case ']':
if (!stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else {
stack.push(s.charAt(i));
}
break;
case '}':
if (!stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
stack.push(s.charAt(i));
}
break;
default:
stack.push(s.charAt(i));
break;
}
}
return s.length() == 0 || stack.isEmpty();//栈为空说明匹配成功,特判空字符串也为匹配成功
}
}