data-structures · intermediate · ~15 min
Use a stack to match nested delimiters.
Check whether the brackets in a string are correctly matched and nested.
Implement int paren_balanced(const char *s) that returns 1 if every (, [, and { is matched with the correct closer in the correct nesting order, else 0. Characters that are not brackets are ignored.
s: a NUL-terminated string that may contain (), [], {}, and any other characters.
int: 1 if balanced, 0 otherwise.
"a(b[c]{d})" -> 1
"(]" -> 0 (wrong closer)
"((" -> 0 (unclosed)
"" -> 1 (empty is balanced)
s: a NUL-terminated string; non-bracket characters are ignored.
int: 1 if all brackets are matched and nested, else 0.
Use a stack to track open brackets.
int paren_balanced(const char *s) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.