1.我的暴力解法
class Solution {public boolean isValid(String s) {Stack<Character> stk=new Stack<Character>();int i=0;if(s.length()%2!=0)return false;for (;i<s.length();i++){if(s.charAt(i)=='('){stk.push('(');}else if(s.charAt(i)=='{'){stk.push('{');}else if(s.charAt(i)=='['){stk.push('[');}else{if(s.charAt(i)==')'){if(!stk.isEmpty()&&stk.peek()=='(')stk.pop();elsereturn false;}else if (s.charAt(i)=='}'){if(!stk.isEmpty()&&stk.peek()=='{')stk.pop();elsereturn false;}else if (s.charAt(i)==']'){if(!stk.isEmpty()&&stk.peek()=='[')stk.pop();elsereturn false;}else{return false;}}}return stk.isEmpty();}
}
2.大佬解法,哈希解法
class Solution {public boolean isValid(String s) {LinkedList<Character> list=new LinkedList<>();list.add('?');if(s.length()%2!=0)return false;HashMap<Character,Character> map=new HashMap<>();map.put('(',')');map.put('[',']');map.put('{','}');map.put('?','?');int i=0;for (;i<s.length();i++){if(map.containsKey(s.charAt(i))){list.add(s.charAt(i));}else if(map.get(list.pollLast())!=s.charAt(i)){return false;}}return list.size()==1;}
}