Optimal: stack of expected closers
Time O(n) Space O(n)For each opener, push the closer you expect. For each closer, the stack must be non-empty and its top must equal it. At the end, the stack must be empty.
s = "([)]"expected closers(stack)
Step 1/3'(' → expect ')'.
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public boolean isValid(String s) {
Deque<Character> expect = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') expect.push(')');
else if (c == '[') expect.push(']');
else if (c == '{') expect.push('}');
else if (expect.isEmpty() || expect.pop() != c) return false;
}
return expect.isEmpty();
}
}Verdict: One pass.