class Solution { public boolean isValid(String s) { if(s==null || s.length() == 0) { return true; } char[] chars = s.toCharArray(); Map<Character,Character> map = new HashMap<Character,Character>(); map.put(')', '('); map.put(']', '['); map.put('}', '{'); Stack<Character> stack = new Stack<Character>(); for(int i = 0; i<chars.length; i++) { if(map.containsValue(chars[i])) { stack.add(chars[i]); } if(map.containsKey(chars[i]) && (stack.empty() || !(stack.pop().equals(map.get(chars[i]))))) { //System.out.println("ddd:"+stack.size()); return false; } /* * if(map.containsKey(chars[i]) && stack==null) { * * return false; } */ } if(!stack.empty()) { return false; } return true; } }