Leetcode学习笔记:#20. Valid Parentheses
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.
实现:
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();
}
思路:
每遇到一个括号的都将另一半都存入栈中,如果遇到反括号则将其栈顶的括号弹出,如果弹出来的反括号不匹配,返回false。