思路:读取字符串中的每一个字符,并与栈顶元素进行比较,如果匹配则栈顶元素出栈,否则进栈。直到全部元素都出栈,否则该括号字符串不合法。需要注意细节。
1 public boolean isValid(String s) { 2 Stack<Character> stack=new Stack<Character>(); 3 for(int i=0;i<s.length();i++){ 4 char t=s.charAt(i); 5 if(t=='(' || t=='[' || t=='{'){ 6 stack.push(t); 7 }else if(!stack.isEmpty()&&(t==')'&&stack.peek()=='(' || t==']'&&stack.peek()=='[' || t=='}'&&stack.peek()=='{')){ 8 stack.pop(); 9 }else{ 10 return false; 11 } 12 } 13 if(stack.isEmpty()){ 14 return true; 15 }else{ 16 return false; 17 } 18 } 19