Question:
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.
import java.util.Stack;
public class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<Character>();
for(int i = 0;i<s.length();i++){
char c = s.charAt(i);
if (c=='{'||c=='['||c=='(') {
st.push(c);
}else if (c=='}'||c==')'||c==']') {
if (st.size()==0) {
return false;
}
char popChar = st.pop();
if (popChar=='{'&&c=='}') {
continue;
}else if (popChar=='('&&c==')') {
continue;
}else if (popChar=='['&&c==']'){
continue;
}
return false;
}
}
return st.size()==0;
}
}