public boolean isValid(String s) {
char[] sa = s.toCharArray();
Stack<Character> stk = new Stack<>();
for(char c : sa){
if(stk.isEmpty()){
if(isOpener(c)){//c is (, { or [
stk.push(c);
}else{//c is ), } or ]
return false;
}
}else{
if(isOpener(c)){//c is (, { or [
stk.push(c);
}else{//c is ), } or ]
char top = stk.peek();
if(compatibleOpenClose(c, top)){
stk.pop();
}else{
return false;
}
}
}
}
if(stk.isEmpty()) return true;
return false;
}
public boolean isOpener(char c){
if(c == '{' || c == '(' || c == '[')return true;
return false;
}
public boolean compatibleOpenClose(char c, char top){
if(top == '(' && c == ')') return true;
if(top == '{' && c == '}') return true;
if(top == '[' && c == ']') return true;
return false;
}