LeetCode 20. 有效的括号
class Solution { public boolean isValid(String s) { //首先边界判断,如果是奇数个 直接返回flase if(s.length() % 2 == 1){ return false ; } //将(){} []存到一个HashMap 中 这样查找用O(1)时间 Map<Character,Character> paris = new HashMap<Character,Character>(); paris.put(')','('); paris.put(']','['); paris.put('}','{'); //用一个辅助栈来保存 Deque<Character> stack = new LinkedList<Character>(); //开始遍历字符串 for(int i=0;i<s.length();i++){ char ch = s.charAt(i); if(paris.containsKey(ch)){ if(stack.isEmpty() || stack.peek() != paris.get(ch)){ return false ; } stack.pop(); }else { stack.push(ch); } } return stack.isEmpty(); } }