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.
1 public class Solution { 2 public boolean isValid(String s) { 3 Stack<Character> stack = new Stack<Character>(); 4 char[] c = s.toCharArray(); 5 for(int i=0;i<c.length;i++){ 6 if(stack.isEmpty() || !is(stack.peek(),c[i])){ 7 stack.push(c[i]); 8 } 9 else{ 10 stack.pop(); 11 } 12 } 13 return stack.isEmpty(); 14 } 15 public boolean is(char a,char b){ 16 if(a=='(') return b==')'; 17 if(a=='{') return b=='}'; 18 if(a=='[') return b==']'; 19 return false; 20 } 21 }
浙公网安备 33010602011771号