题目
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.
解析
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
char[] ch = s.toCharArray();
int n = ch.length;
for (int i = 0; i < n; i++) {
char c = ch[i];
if (c == '{' || c == '[' || c == '(') stack.push(c);
else {
if (stack.size() == 0) return false;
char cc = stack.pop();
if (cc == '{' && c != '}') return false;
if (cc == '[' && c != ']') return false;
if (cc == '(' && c != ')') return false;
}
}
if (!stack.isEmpty()) return false;
return true;
}
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}