Matching brackets
Bracket matching uses a stack: push each opening bracket, check each closing one against the top and pop it if they pair, and the string is valid only if the stack ends empty, so {[()]} passes and ([)] fails.
{[()]} matches, ([)] doesn't: same number of brackets, but ) arrives while [ is still open. Compilers, JSON parsers and editors' bracket highlighting all have to answer this. The rule is: the last bracket opened must be the first one closed. That is a stack.
The rule: opening goes on, closing checks the top
Read from left to right:
- An opening bracket: push it.
- A closing bracket: if the stack is empty, it has nothing to match, wrong; if the top isn't its partner, wrong; if it is, pop.
- At the end: anything still on the stack is a bracket never closed, wrong; an empty stack, right.
topChecking ([]{}): right after reading {, what is on the stack, from bottom to top?
( is pushed, [ is pushed; ] matches the top [, so [ is popped; then { is pushed. That leaves ( and {, with { on top.Which 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 ends empty. In ([)] the top is [ when ) arrives; ((()) ends with one ( left over.How deep does it nest
✓The string holds only ( and ), and they match. Work out the deepest nesting, that is, the most on the stack at once.
3
1#include <stdio.h>2 3int main(void) {4 const char *s = "(()(()))()";5 int depth = 0, best = 0;6 // ( adds 1 to depth (keep the largest), ) takes 1 off7 printf("%d\n", best);8 return 0;9}
Writing it
1#include <stdio.h>2 3// are they a pair4int pair(char open, char close) {5 return (open == '(' && close == ')') ||6 (open == '[' && close == ']') ||7 (open == '{' && close == '}');8}9 10int match(const char *s) {11 char st[100];12 int top = -1;13 for (int i = 0; s[i] != '\0'; i++) {14 char c = s[i];15 if (c == '(' || c == '[' || c == '{') {16 st[++top] = c;17 } else if (c == ')' || c == ']' || c == '}') {18 if (top == -1) return 0; // too many closing19 if (!pair(st[top], c)) return 0; // the wrong pair20 top--;21 }22 // anything else is skipped23 }24 return top == -1; // too many opening: not empty25}26 27int main(void) {28 const char *tests[] = {"{[()]}", "([)]", "(()", "())", "a[i] = f(b[j]);"};29 for (int k = 0; k < 5; k++)30 printf("%-16s %s\n", tests[k], match(tests[k]) ? "yes" : "no");31 return 0;32}
{[()]} yes
([)] no
(() no
()) no
a[i] = f(b[j]); yes
Look at the last example: characters other than brackets are skipped, so the function can check a real line of code.
Fill in the last line so all three cases come out right: the program should print 1 0 0.
1#include <stdio.h>2 3int pair(char open, char close) {4 return (open == '(' && close == ')') ||5 (open == '[' && close == ']') ||6 (open == '{' && close == '}');7}8 9int match(const char *s) {10 char st[100];11 int top = -1;12 for (int i = 0; s[i] != '\0'; i++) {13 char c = s[i];14 if (c == '(' || c == '[' || c == '{') {15 st[++top] = c;16 } else if (c == ')' || c == ']' || c == '}') {17 if (top == -1 || !pair(st[top], c)) return 0;18 top--;19 }20 }21 return ;22}23 24int main(void) {25 printf("%d %d %d\n", match("{[()]}"), match("(()"), match("())"));26 return 0;27}
return 1;, (() would count as balanced and the program would print 1 1 0.Write match
✓Finish match: return 1 when the brackets match, 0 otherwise. All three ways of failing must be caught.
1 0 0 0
1#include <stdio.h>2 3int pair(char open, char close) {4 return (open == '(' && close == ')') ||5 (open == '[' && close == ']') ||6 (open == '{' && close == '}');7}8 9int match(const char *s) {10 char st[100];11 int top = -1;12 for (int i = 0; s[i] != '\0'; i++) {13 char c = s[i];14 // opening: push; closing: empty or no pair returns 0, a pair pops15 }16 return 0; // change to: right only if the stack is empty17}18 19int main(void) {20 printf("%d %d %d %d\n", match("([]{})"), match("(]"), match("(("), match("))"));21 return 0;22}
The three ways it fails
| Example | What's wrong | Found when |
|---|---|---|
()) | one closing too many | the second ) finds the stack already empty |
(() | one opening too many | at the end, a ( is still on the stack |
([)] | the wrong pair | ) arrives with [ on top |
The one most often missed is the second: checking only inside the loop and forgetting the final return top == -1, so (() passes.
stack
([Checking {[(])}, at which character (counting from 0) is the mistake found?
1#include <stdio.h>2 3int main(void) {4 const char *s = "{[(])}";5 char st[10];6 int top = -1, at = -1;7 for (int i = 0; s[i] != '\0' && at < 0; i++) {8 char c = s[i];9 if (c == '(' || c == '[' || c == '{') st[++top] = c;10 else if (top == -1 || !((st[top] == '(' && c == ')') || (st[top] == '[' && c == ']') || (st[top] == '{' && c == '}'))) at = i;11 else top--;12 }13 printf("%d\n", at);14 return 0;15}
This match forgets the final empty-stack check. What does it print?
1#include <stdio.h>2 3int match(const char *s) {4 char st[100];5 int top = -1;6 for (int i = 0; s[i] != '\0'; i++) {7 if (s[i] == '(') {8 st[++top] = '(';9 } else if (s[i] == ')') {10 if (top == -1) return 0;11 top--;12 }13 }14 return 1;15}16 17int main(void) {18 printf("%d %d\n", match("(()"), match("())"));19 return 0;20}
(() ends with one ( still on the stack, but the function just does return 1, so it counts as balanced; in ()) the stack is already empty at the second ), so the loop catches it. Of the three failures this is the easiest to miss: too many opening brackets.Which 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 top == -1 catches.Summary
Matching brackets: the last opened is the first closed
- Opening bracket: push
- Closing bracket: an empty stack or no pair with the top is wrong; a pair pops
- At the end the stack must be empty
1if (open) st[++top] = c;2else if (top == -1 || !pair(st[top], c)) return 0;3else top--;4return top == -1;