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.
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
if (s.length()==0){
return true;
}
int len = s.length();
for (int i=0;i<len;i++){
switch (s.charAt(i)){
case '(':{
stack.push('(');
break;
}
case '{':{
stack.push('{');
break;
}
case '[':{
stack.push('[');
break;
}
case ')':{
if (!stack.empty()&&stack.peek()=='('){ //判断是否为空不然有异常
stack.pop();
break;
}else{
return false;
}
}
case '}':{
if (!stack.empty()&&stack.peek()=='{'){
stack.pop();
break;
}else{
return false;
}
}
case ']':{
if (!stack.empty()&&stack.peek()=='['){
stack.pop();
break;
}else{
return false;
}
}
default:break;
}
}
if (stack.empty()){
return true;
}else{
return false;
}
}