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.
Analysis:
This is a simple problem, but easy to make mistake when implementing. Idea of which is to utilize a stack to match symbols.
public class Solution {
public boolean isValid(String s) {
if(s.length()<=1) return false;
Stack<Character> symbol = new Stack<Character>();
for (int i =0; i<s.length(); i++){
if(s.charAt(i) == '(' || s.charAt(i)=='{' || s.charAt(i)=='[') symbol.push(s.charAt(i));
else if (s.charAt(i)==')') {
if(symbol.isEmpty() == true || symbol.pop()!='(') return false;
}
else if (s.charAt(i)=='}') {
if(symbol.isEmpty() == true || symbol.pop()!='{') return false;
}
else if (s.charAt(i)==']') {
if(symbol.isEmpty() == true || symbol.pop()!='[') return false;
}
else return false;
}
if (symbol.isEmpty() == true) return true;
return false;
}
}
Note that always check if stack is empty before .pop().