[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.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
解法
思路
是个很简单的括号匹配问题,用栈来解决。碰到左括号入栈。碰到右括号,若此时栈为空,则直接返回false,如果不为空,则与栈顶括号对比,如果匹配成功则栈顶元素出栈,然后继续循环。如果匹配失败,直接返回false。等所有括号都扫描完成后,如果栈内为空,则返回true,否则返回false。
代码
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length();i++){
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
else{
if(stack.isEmpty()) return false;
if(s.charAt(i) == ')'&&stack.pop()!='(') return false;
if(s.charAt(i) == ']'&&stack.pop()!='[') return false;
if(s.charAt(i) == '}'&&stack.pop()!='{') return false;
}
}
return stack.isEmpty();
}
}
更优雅的代码(原理相同)
class Solution {
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();
}
}