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.
example:
([]) true
[]() true
[ false
(( false
(([] false
解题:
这道题可以用栈来实现
如果发现是'(','[','{'就压入栈,如果是')',']','}'就弹出栈顶元素并比较,如果不相等return false;
最后如果栈中还有元素,则return false
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
if(s.length() == 0 || s.length() % 2 == 1){return false;}
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;}
if((s.charAt(i)==')' && !stack.pop().equals('(')) ||
(s.charAt(i)==']' && !stack.pop().equals('[')) ||
(s.charAt(i)=='}' && !stack.pop().equals('{')) ){
return false;
}
}
}
return stack.empty();
}
}