题目
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.
答案
看到左括号就push 右括号
看到右括号就看看top()是什么,如果不match就return false,如果stack为空也return false
过完一边字符串后,最后看看stack是否为空,如果不为空,肯定也是invalid
public class Solution {
public boolean isValid(String s) {
Stack<Character> stk = new Stack<Character>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == '(') stk.push(')');
else if(c == '{') stk.push('}');
else if(c == '[') stk.push(']');
else if(stk.isEmpty() || c != stk.pop()) return false;
}
return stk.isEmpty();
}
}