Kodewick
Start learning →
Matching brackets12 / 50

Matching brackets

Lesson 12 of 50 · Part 3 · Stacks and queues · about 12 minutes

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:

  1. An opening bracket: push it.
  2. 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.
  3. At the end: anything still on the stack is a bracket never closed, wrong; an empty stack, right.
stack (bottom on the left)0123

Checking {[()]}: the stack holds the opening brackets not yet closed, and each closing one is matched with the top
Choose one

Checking ([]{}): right after reading {, what is on the stack, from bottom to top?

Choose allPick all that apply

Which strings are balanced? (You can pick more than one.)

Exercise 1

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.

It should print
3
exercise1.c
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}
Output
Press Run or Ctrl+Enter

Writing it

main.c
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}
Output
{[()]}           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 inTap one to fill a blank; tap a blank to take it back

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}
Exercise 2

Write match

Finish match: return 1 when the brackets match, 0 otherwise. All three ways of failing must be caught.

It should print
1 0 0 0
exercise2.c
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}
Output
Press Run or Ctrl+Enter

The three ways it fails

ExampleWhat's wrongFound when
())one closing too manythe second ) finds the stack already empty
(()one opening too manyat 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 ([)]: when ) arrives the top is [, which does not match, so it fails right there
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Choose one

Which kind of error is [[]?

Summary

Take-away

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;