20. Valid Parentheses
- Difficulty: Easy
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 class Solution {
public boolean isValid(String s) {
if(s==null||s.length()<=0)
return true;
Stack<Integer> stack=new Stack<>();
char[] chars=s.toCharArray();
boolean flag=true;
for(int i=0;i<s.length();i++){
switch (chars[i]){
case '(':
stack.push(-1);
break;
case'[':
stack.push(-2);
break;
case'{':
stack.push(-3);
break;
case ')':
if(stack.isEmpty()||1+stack.pop()!=0)
flag&=false;
break;
case']':
if(stack.isEmpty()||2+stack.pop()!=0)
flag&=false;
break;
case'}':
if(stack.isEmpty()||3+stack.pop()!=0)
flag&=false;
break;
default:
break;
}
if(!flag)
break;
}
return flag&stack.isEmpty();
}
}