20. Valid Parentheses
Last updated
Last updated
ex: if have '(', replace ')' , one by one...
/*
time: O(n)
space: O(n)
*/
class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) return true;
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if ('(' == c) {
stack.push(')');
} else if ('[' == c) {
stack.push(']');
} else if ('{' == c) {
stack.push('}');
} else if (stack.isEmpty() || stack.pop() != c) {
return false;
}
}
return stack.isEmpty(); // notice here!
}
}
or
class Solution {
public boolean isValid(String s) {
// if "(" push ")", or ")" pop, finally statck is empty => true
Stack<Character> stack = new Stack<>();
for (Character c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) return false;
Character top = stack.pop();
if (!(top == '(' && c == ')' ||
top == '[' && c == ']' ||
top == '{' && c == '}')) {
return false;
}
}
}
return stack.isEmpty();
}
}