Stack · Easy
Valid Parentheses: the idea to remember.
Determine whether a string of brackets is correctly matched and nested.
The core insight
Push expected closing brackets; each closer must match the top expectation.
Why it works
The stack records outstanding closing obligations in reverse opening order.
The mistake to avoid
An empty stack is required at the end; opening brackets alone are invalid.
Time: O(n)Space: O(n)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
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();
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.