public static boolean isValid(String s){ Map<Character, Character> map = new HashMap<>(); map.put(‘(‘,‘)‘); map.put(‘{‘,‘}‘); map.put(‘[‘,‘]‘); Stack stack = new Stack(); for (char c : s.toCharArray()) { if (map.containsKey(c)){ stack.push(c); }else { //如果不为null,且值相等则出栈 if (!stack.isEmpty()&&map.get(stack.peek()).equals(c)){ stack.pop(); }else { return false; } } } //如果返回true的话,可能存在栈里面还有值的情况 return stack.isEmpty(); }