Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example:
s = "()[]{}"trueExample 2:
s = "([)]"falseThe key insight is that the most recent unmatched opening bracket must match the next closing bracket. This "last-in, first-out" behavior is exactly what a stack provides!
When we see an opening bracket, we push it onto the stack. When we see a closing bracket, we check if it matches the top of the stack (most recent opening bracket).
This is a classic Stack problem. The stack naturally handles the nested and ordered nature of valid parentheses.
(, {, or [: push onto stackfalse (no matching opening)falsetrue if stack is empty, false otherwise"([)]" is invalid1class Solution {
2 public boolean isValid(String s) {
3 // Stack to track opening brackets
4 Stack<Character> stack = new Stack<>();
5
6 for (char c : s.toCharArray()) {
7 // Push opening brackets onto stack
8 if (c == '(' || c == '{' || c == '[') {
9 stack.push(c);
10 }
11 // For closing brackets, check if they match
12 else {
13 // Stack empty means no matching opening bracket
14 if (stack.isEmpty()) {
15 return false;
16 }
17
18 char top = stack.pop();
19
20 // Check if brackets match
21 if (c == ')' && top != '(') return false;
22 if (c == '}' && top != '{') return false;
23 if (c == ']' && top != '[') return false;
24 }
25 }
26
27 // Stack should be empty if all brackets matched
28 return stack.isEmpty();
29 }
30}
31