栈与队列:
/** * 20. 有效的括号 * @param s * @return */ public boolean isValid(String s) { Deque<Character> deque = new LinkedList<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); //碰到左括号,就把相应的右括号入栈 if (ch == '(') { deque.push(')'); }else if (ch == '{') { deque.push('}'); }else if (ch == '[') { deque.push(']'); } else if (deque.isEmpty() || deque.peek() != ch) { return false; }else { //如果是右括号判断是否和栈顶元素匹配 deque.pop(); } } //最后判断栈中元素是否匹配 return deque.isEmpty(); }
标签:deque,ch,return,括号,else,二刷,push,Leetcode,Days08 From: https://www.cnblogs.com/LinxhzZ/p/17445825.html