leetcode-20. Valid Parentheses
题目:
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.
基本思路就用栈去匹配最近的一个左括号。
public class Solution {
public boolean isValid(String s) {
if(s.length()<1)return true;
Stack<Character> sta = new Stack<Character>();
sta.push(s.charAt(0));
for(int i = 1 ; i < s.length() ; i++){
char c = s.charAt(i);
if(c=='(' ||c=='{' ||c=='[') sta.push(c);
if(c==')') if(sta.isEmpty() || '('!=sta.pop()) return false;
if(c=='}') if(sta.isEmpty() || '{'!=sta.pop()) return false;
if(c==']') if(sta.isEmpty() || '['!=sta.pop()) return false;
}
return sta.isEmpty();
}
}

585

被折叠的 条评论
为什么被折叠?



