题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
java代码
public boolean isValid (String s) { // write code here Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++){ if (s.charAt(i) == '[' || s.charAt(i) == '(' || s.charAt(i) == '{'){ stack.push(s.charAt(i)); }else { if(stack.empty()) return false; switch (s.charAt(i)){ case ']':if (stack.pop() != '[') return false;break; case '}':if (stack.pop() != '{') return false;break; case ')':if (stack.pop() != '(') return false;break; default:break; } } } if (stack.empty()){ return true; } return false; }