Valid Parentheses
Push openers; on a closer, the stack top must be its match.
3 min read
stack parsing
Problem#
Given a string containing only ()[]{}, return whether all brackets are correctly closed and properly nested.
Examples#
"()"→true"()[]{}"→true"(]"→false"([)]"→false
Constraints#
1 <= s.length <= 10^4.
Approach#
Push each opener onto a stack. For each closer, pop and compare against the expected match. At the end, the stack must be empty.
Solution#
class Solution {public: bool isValid(string s) { stack<char> st; for (char c : s) { if (c == '(' || c == '[' || c == '{') st.push(c); else { if (st.empty()) return false; char t = st.top(); st.pop(); if ((c == ')' && t != '(') || (c == ']' && t != '[') || (c == '}' && t != '{')) return false; } } return st.empty(); }};func isValid(s string) bool { st := []byte{} for i := 0; i < len(s); i++ { c := s[i] if c == '(' || c == '[' || c == '{' { st = append(st, c) } else { if len(st) == 0 { return false } t := st[len(st)-1] st = st[:len(st)-1] if (c == ')' && t != '(') || (c == ']' && t != '[') || (c == '}' && t != '{') { return false } } } return len(st) == 0}class Solution: def isValid(self, s: str) -> bool: match = {')': '(', ']': '[', '}': '{'} st = [] for c in s: if c in '([{': st.append(c) else: if not st or st[-1] != match[c]: return False st.pop() return not stfunction isValid(s) { const match = { ')': '(', ']': '[', '}': '{' }; const st = []; for (const c of s) { if (c === '(' || c === '[' || c === '{') { st.push(c); } else { if (st.length === 0 || st[st.length - 1] !== match[c]) return false; st.pop(); } } return st.length === 0;}class Solution { public boolean isValid(String s) { Deque<Character> st = new ArrayDeque<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') { st.push(c); } else { if (st.isEmpty()) return false; char t = st.pop(); if ((c == ')' && t != '(') || (c == ']' && t != '[') || (c == '}' && t != '{')) return false; } } return st.isEmpty(); }}function isValid(s: string): boolean { const match: Record<string, string> = { ')': '(', ']': '[', '}': '{' }; const st: string[] = []; for (const c of s) { if (c === '(' || c === '[' || c === '{') { st.push(c); } else { if (st.length === 0 || st[st.length - 1] !== match[c]) return false; st.pop(); } } return st.length === 0;}Editorial#
The “most recently opened bracket must match the next closer” invariant is exactly what a stack expresses. Every push pairs with at most one pop; mismatches and leftover openers both signal invalid input.
Complexity#
- Time: O(n).
- Space: O(n).
Concept revision#
Related#