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) {
int len=s.length();
char[] sym=new char[len];
int count=0;
for(int i=0;i<len;i++)
{
switch (s.charAt(i))
{
case '(':
sym[count]='(';
count++;
break;
case ')':
count--;
if(count<0) return false;
if(sym[count]!='(') return false;
break;
case '[':
sym[count]='[';
count++;
break;
case ']':
count--;
if(count<0) return false;
if(sym[count]!='[') return false;
break;
case '{':
sym[count]='{';
count++;
break;
case '}':
count--;
if(count<0) return false;
if(sym[count]!='{') return false;
break;
default:
break;
}
}
if(count!=0) return false;
else return true;
}
}