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) { Stack<Character> stack = new Stack<Character>(); int len = s.length(); for(int i = 0; i<len; i++){ if(!stack.empty()){ char top = stack.peek(); char c = s.charAt(i); // 注意match 两个字符的顺序 if(!match(top,c)){ stack.push(c); }else{ stack.pop(); } }else{ stack.push(s.charAt(i)); } } if(!stack.empty()){ return false; }else{ return true; } } public boolean match(char a, char b){ if(a == '(' && b ==')'){ return true; } else if(a == '{' && b =='}'){ return true; }else if(a == '[' && b ==']'){ return true; }else{ return false; } } }

浙公网安备 33010602011771号