Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
//注意英语语序,是无效的意思就是可以匹配成功的。
//注意英语语序,是无效的意思就是可以匹配成功的。 public boolean isValid(String s) { Map<Character, Character> map = new HashMap<>(); map.put('(', ')'); map.put('[', ']'); map.put('{', '}'); Stack<Character> stack = new Stack<Character>(); if (s.length() % 2 != 0 || s == null || s.length() == 0) return false; for (int i = 0; i < s.length(); i++) { if ((s.charAt(i) == '[') || s.charAt(i) == '{' || s.charAt(i) == '(') stack.push(s.charAt(i)); //注意先判断size() else if (stack.size()>0&&(map.get(stack.peek()) ==s.charAt(i) )) stack.pop(); else return false; } return stack.empty(); }