Each subpattern solves a specific type of problem. Click on a card to view its template.
Template for: Bracket Matching / Validity
Whenever you encounter an opening bracket '(', '[', or '{', push it onto the stack.
On a closing bracket, check that the stack is non-empty and the top matches. If not, the string is invalid.
After scanning all characters, the stack must be empty — any leftovers mean unmatched openers.
1// Bracket matching — push openers, match on closers2bool isValid(string s)3{4 stack<char> st;56 for (char c : s)7 {8 if (c == '(' || c == '[' || c == '{')9 {10 st.push(c); // push opener11 }12 else13 {14 // closer — stack must have a matching opener15 if (st.empty()) return false;1617 char top = st.top(); st.pop();1819 if ((c == ')' && top != '(') ||20 (c == ']' && top != '[') ||21 (c == '}' && top != '{'))22 {23 return false; // mismatched pair24 }25 }26 }2728 return st.empty(); // all openers matched29}
Sharpen your skills with hand-picked problems.
LeetCode #20
LeetCode #921
LeetCode #1249
LeetCode #32
LeetCode #739
LeetCode #496
LeetCode #503
LeetCode #901
LeetCode #907
LeetCode #84
LeetCode #85
LeetCode #42
LeetCode #1793
LeetCode #150
LeetCode #224
LeetCode #227
LeetCode #456
LeetCode #962
LeetCode #1944
LeetCode #394
LeetCode #856
LeetCode #726
LeetCode #341