1 题目
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.
2 思路
这题是真心比较简单了,一个栈就可以解决了。需要主要empty的情况。
3 代码:
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(Character ch : s.toCharArray()){ switch (ch) { case '(': case '[': case '{': stack.push(ch); break; case ')': if(stack.empty() || stack.peek() != '(') { return false; }else{ stack.pop(); } break; case '}': if(stack.empty() || stack.peek() != '{') { return false; }else{ stack.pop(); } break; case ']': if(stack.empty() || stack.peek() != '[') { return false; }else{ stack.pop(); } break; default: return false; } } return stack.empty(); }