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.
Subscribe to see which companies asked this question
Use if-else:
public class Solution {
public boolean isValid(String s) {
Stack<Character> st=new Stack<Character>();
int len=s.length();
for(int i=0;i<len;++i){
char temp=s.charAt(i);
if(temp=='('||temp=='['||temp=='{'){
st.push(temp);
}
else{
if(st.empty())
return false;
char ch=st.pop();
if(temp==')'&&ch!='(')
return false;
else if(temp==']'&&ch!='[')
return false;
else if(temp=='}'&&ch!='{')
return false;
}
}
return st.empty();
}
}
use switch:
public class Solution {
public boolean isValid(String s) {
Stack<Character> st=new Stack();
for(int i=0;i<s.length();++i){
switch(s.charAt(i)){
case('('):
case('{'):
case('['):{
st.push(s.charAt(i));
break;
}
case(')'):{
if(st.empty()||st.pop()!='(')
return false;
break;
}
case(']'):{
if(st.empty()||st.pop()!='[')
return false;
break;
}
case('}'):{
if(st.empty()||st.pop()!='{')
return false;
break;
}
default:break;
}
}
return st.empty();
}
}