class Solution {
public boolean isValid(String s) {
if(s.length() % 2 != 0){
return false;
}
Stack<Character> stack = new Stack<Character>();
char charArray[] = s.toCharArray();
for(int i = 0;i < charArray.length;i++){
char c = charArray[i];
if(c == '('){
stack.push('(');
}else if(c == '[' ){
stack.push('[');
}else if(c == '{'){
stack.push('{');
}else{
if(stack.isEmpty()) return false;
char top = stack.peek();
if(top == '(' && c == ')' || top == '[' && c == ']' || top == '{' && c == '}'){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}
}
|