public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(int i=0; i< s.length(); i++){ if(!stack.isEmpty()){ char c = stack.peek(); if(match(c, s.charAt(i))){ stack.pop(); }else{ stack.push(s.charAt(i)); } }else{ stack.push(s.charAt(i)); } } if(stack.isEmpty()){ return true; }else{ return false; } } public boolean match(char a, char b){ if( a == ‘(‘ && b == ‘)‘){ return true; }else if( a == ‘[‘ && b == ‘]‘){ return true; }else if( a == ‘{‘ && b == ‘}‘){ return true; } return false; } }
原文:http://www.cnblogs.com/RazerLu/p/3532314.html