Example 1 — Balanced brackets
Three test strings.
#include <stdio.h>
static int balanced(const char *s) {
char st[64];
int top = -1;
for (; *s; s++) {
char ch = *s;
if (ch == '(' || ch == '[' || ch == '{') {
st[++top] = ch;
} else if (ch == ')' || ch == ']' || ch == '}') {
if (top < 0) return 0;
char o = st[top--];
if ((ch == ')' && o != '(') ||
(ch == ']' && o != '[') ||
(ch == '}' && o != '{')) return 0;
}
}
return top < 0;
}
int main(void) {
const char *tests[] = {"{[()]}", "([)]", "(("};
for (int i = 0; i < 3; i++)
printf("%s: %s\n", tests[i], balanced(tests[i]) ? "balanced" : "not balanced");
return 0;
} How It Works
{[()]}closes in exact reverse order of opening.([)]fails because)meets[on top.((ends with unclosed brackets on the stack.
