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<Character> stack = new Stack<Character>();
for (int i = 0; i<s.length();i++){
char ss = s.charAt(i);
if (ss=='('||ss=='['||ss=='{'){
stack.push(ss);
}
else if (ss==')'||ss==']'||ss=='}'){
if (stack.size()==0) return false;
char cpop = stack.pop();
if (cpop=='('&&ss==')')
{
continue;
}
else if (cpop=='['&&ss==']')
{
continue;
}
else if (cpop=='{'&&ss=='}')
{
continue;
}
return false;
}
}
return stack.empty();
}
}