Matching brackets
Bracket matching uses a stack: push each opening bracket, check each closing one against the top, and end with an empty stack, so {[()]} passes and ([)] fails; the STL way uses std::stack<char>.
{[()]} matches and ([)] doesn't: the counts are the same, but ) arrives while [ is still open. Compilers, JSON parsers and an editor's bracket highlighting all have to answer this. The rule is: the bracket opened last must be closed first. That's exactly a stack.
The rule: push openers, check closers against the top
Read from left to right:
- An opening bracket: push it.
- A closing bracket: if the stack is empty, it has no partner: wrong. If the top isn't its partner: wrong. If it is: pop.
- At the end: anything left on the stack is a bracket never closed: wrong. An empty stack: right.
topChecking ([]{}): just after reading {, what is in the stack, bottom to top?
( is pushed, [ is pushed; ] matches the top [, so [ is popped; { is pushed. Now the stack holds ( and {, with { on top.Which bracket strings are balanced? (You can pick more than one.)
{[]}() and [(){}], every closing bracket matches the top of the stack at that moment, and the stack is empty at the end. In ([)] the top is [ when ) arrives; ((()) ends with one ( left over.How deep does it nest?
✓The string holds only ( and ), and they match. Find the deepest nesting, that is, how many are on the stack at its highest.
3
1#include <iostream>2#include <string>3using namespace std;4 5int main() {6 string s = "(()(()))()";7 int depth = 0, best = 0;8 // ( adds 1 to depth (keep the largest), ) takes 1 away9 cout << best << "\n";10 return 0;11}
Writing it
First use a char array as the stack, with t the index of the top, just like last lesson's array stack.
1#include <iostream>2#include <string>3using namespace std;4 5// are they a pair?6bool isPair(char open, char close) {7 return (open == '(' && close == ')') ||8 (open == '[' && close == ']') ||9 (open == '{' && close == '}');10}11 12bool match(const string& s) {13 char st[100];14 int t = -1;15 for (char c : s) {16 if (c == '(' || c == '[' || c == '{') {17 st[++t] = c;18 } else if (c == ')' || c == ']' || c == '}') {19 if (t == -1) return false; // too many closers20 if (!isPair(st[t], c)) return false; // wrong partner21 t--;22 }23 // anything else is skipped24 }25 return t == -1; // too many openers: not empty26}27 28int main() {29 string tests[] = {"{[()]}", "([)]", "(()", "())", "a[i] = f(b[j]);"};30 for (const string& s : tests)31 cout << s << string(18 - s.size(), ' ') << (match(s) ? "ok" : "wrong") << "\n";32 return 0;33}
{[()]} ok
([)] wrong
(() wrong
()) wrong
a[i] = f(b[j]); ok
Look at the last example: anything that isn't a bracket is skipped, so this function can check a real line of code. const string& passes the string by reference, without copying it.
Fill in the last line so all three cases come out right: the program should print 1 0 0.
1#include <iostream>2#include <string>3using namespace std;4 5bool isPair(char open, char close) {6 return (open == '(' && close == ')') ||7 (open == '[' && close == ']') ||8 (open == '{' && close == '}');9}10 11bool match(const string& s) {12 char st[100];13 int t = -1;14 for (char c : s) {15 if (c == '(' || c == '[' || c == '{') {16 st[++t] = c;17 } else if (c == ')' || c == ']' || c == '}') {18 if (t == -1 || !isPair(st[t], c)) return false;19 t--;20 }21 }22 return ;23}24 25int main() {26 cout << match("{[()]}") << " " << match("(()") << " " << match("())") << "\n";27 return 0;28}
return true;, (() would count as balanced and the output would be 1 1 0.Write match
✓Fill in match: true when the brackets match, false otherwise. It has to catch all three kinds of error.
1 0 0 0
1#include <iostream>2#include <string>3using namespace std;4 5bool isPair(char open, char close) {6 return (open == '(' && close == ')') ||7 (open == '[' && close == ']') ||8 (open == '{' && close == '}');9}10 11bool match(const string& s) {12 char st[100];13 int t = -1;14 for (char c : s) {15 // opener: push; closer: empty stack or no pair means false, a pair means pop16 }17 return false; // make it: right only if the stack is empty18}19 20int main() {21 cout << match("([]{})") << " " << match("(]") << " " << match("((") << " " << match("))") << "\n";22 return 0;23}
Three ways to go wrong
| Example | What's wrong | Found when |
|---|---|---|
()) | Too many closers | At the second ) the stack is already empty |
(() | Too many openers | After the end a ( is still on the stack |
([)] | Wrong partner | At ) the top is [ |
stack
( index 0[ index 1 · meets )The easiest one to miss is the second: checking only inside the loop and forgetting the final return t == -1 lets (() pass as correct.
Checking {[(])}, at which character (counting from 0) is the error found?
1#include <iostream>2#include <string>3using namespace std;4 5int main() {6 string s = "{[(])}";7 char st[10];8 int t = -1, at = -1;9 for (int i = 0; i < (int)s.size() && at < 0; i++) {10 char c = s[i];11 if (c == '(' || c == '[' || c == '{') st[++t] = c;12 else if (t == -1 || !((st[t] == '(' && c == ')') || (st[t] == '[' && c == ']') || (st[t] == '{' && c == '}'))) at = i;13 else t--;14 }15 cout << at << "\n";16 return 0;17}
This match has only one kind of bracket, so the stack only ever holds ( and it just keeps the height t. It forgets the empty check at the end. What does it print?
1#include <iostream>2#include <string>3using namespace std;4 5bool match(const string& s) {6 int t = -1;7 for (char c : s) {8 if (c == '(') {9 t++;10 } else if (c == ')') {11 if (t == -1) return false;12 t--;13 }14 }15 return true;16}17 18int main() {19 cout << match("(()") << " " << match("())") << "\n";20 return 0;21}
(() ends with one ( left (t is 0), but the function just does return true, so it counts as balanced; in ()) the stack is already empty when the second ) arrives, so the loop catches it. Of the three errors, this one is the easiest to miss: too many opening brackets.What kind of error is [[]?
[ and [ are pushed, ] matches one of them, and one [ is left at the end: too many opening brackets, which only the final return t == -1 catches.With the STL
With std::stack<char> you no longer care how big the array is or how t moves. Add a common trick: on an opening bracket, push the closing bracket it needs. On a closing bracket just check that it's the same character as the top, and isPair goes away.
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6bool match(const string& s) {7 stack<char> st;8 for (char c : s) {9 if (c == '(') st.push(')');10 else if (c == '[') st.push(']');11 else if (c == '{') st.push('}');12 else if (c == ')' || c == ']' || c == '}') {13 if (st.empty() || st.top() != c) return false;14 st.pop();15 }16 }17 return st.empty();18}19 20int main() {21 string tests[] = {"{[()]}", "([)]", "(()", "())"};22 for (const string& s : tests)23 cout << s << " " << (match(s) ? "ok" : "wrong") << "\n";24 return 0;25}
{[()]} ok
([)] wrong
(() wrong
()) wrong
The order in st.empty() || st.top() != c matters: when the left side of || is true the right side isn't evaluated, so top() is never called on an empty stack (that's undefined behaviour).
| Version | The stack | Per character | In total |
|---|---|---|---|
| By hand | char st[100] plus the index t | O(1) | O(n) time, up to O(n) stack space |
| STL | stack<char> (a deque inside) | push / top / pop all O(1) | O(n) time, O(n) stack space |
In interviews: "Valid parentheses" is nearly everyone's first stack problem. A stack<char> or just a string used as a stack (push_back, back, pop_back) both work; don't forget the final return st.empty(), or to check for empty when a closer arrives.
In the STL version, the test is written st.top() != c || st.empty() (the two sides swapped). What happens when a ) is checked?
|| works left to right and skips the right side only when the left is true. Swapped, an empty stack runs st.top() first: top() on an empty stack is undefined behaviour, which may read garbage or crash. So the empty test always goes on the left.Summary
Matching brackets: the last opened is the first closed
- Opener: push it (or push the closer it needs)
- Closer: an empty stack or no pair with the top is an error; a pair means pop
- At the end the stack must be empty
- Check empty() before top()
1if (c == '(') st.push(')');2else if (c == ')') {3 if (st.empty() || st.top() != c) return false;4 st.pop();5}6return st.empty();