题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
比较好理解的方式,直观按照题意结题:
public boolean isValid (String s) { // write code here // 奇数一定不合法 int len = s.length(); if((len & 1) == 1) return false; Deque<Character> stack = new ArrayDeque<>(); for (int i = 0; i < len; i++) { char cur = s.charAt(i); if(cur == '(' || cur == '{' || cur == '['){ stack.push(cur); }else{ if(stack.isEmpty()) return false; char top = stack.peek(); if(cur == ')' && top == '('){ stack.pop(); }else if(cur == '}' && top == '{'){ stack.pop(); }else if(cur == ']' && top == '['){ stack.pop(); }else{ return false; } } } return stack.isEmpty(); }