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.
Java:
public class Solution {
public boolean isValid(String s) {
Stack<Integer> st = new Stack<Integer>();
for(int i=0; i<s.length(); i++)
{
if(s.charAt(i)=='{')
{
st.push(1);
}else if(s.charAt(i) =='(')
{
st.push(2);
}
else if(s.charAt(i) =='[')
{
st.push(3);
}else if(s.charAt(i) =='}')
{
if(st.empty()||st.pop() !=1 )
return false;
}else if(s.charAt(i) ==')')
{
if(st.empty() || st.pop() !=2 ) return false;
}else if(s.charAt(i) ==']')
{
if(st.empty() || st.pop() !=3 ) return false;
}
}
if(!st.empty()) return false;
return true;
}
}