64 lines
1.6 KiB
C
64 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdbool.h>
|
|
|
|
bool brackets(const char *code) {
|
|
int stack[100];
|
|
int top = -1;
|
|
|
|
for (int i = 0; code[i] != '\0'; i++) {
|
|
if (code[i] == '(' || code[i] == '[' || code[i] == '{' || code[i] == '<') {
|
|
stack[++top] = i;
|
|
} else if (code[i] == ')' || code[i] == ']' || code[i] == '}' || code[i] == '>') {
|
|
if (top == -1) {
|
|
printf("Unexpected closing bracket %c in %d \n", code[i], i);
|
|
return false;
|
|
}
|
|
|
|
int opening = stack[top--];
|
|
char expected_opening = 0;
|
|
|
|
if (code[i] == ')') {
|
|
expected_opening = '(';
|
|
} else if (code[i] == ']') {
|
|
expected_opening = '[';
|
|
} else if (code[i] == '}') {
|
|
expected_opening = '{';
|
|
} else if (code[i] == '>') {
|
|
expected_opening = '<';
|
|
}
|
|
|
|
if (code[opening] != expected_opening) {
|
|
printf("Crossed bracket %c in %d, expected %c \n", code[i], i, expected_opening);
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (top != -1) {
|
|
int opening = stack[top];
|
|
printf("Unclosed bracket %c in %d\n", code[opening], opening);
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
int main() {
|
|
char code[100];
|
|
fgets(code, sizeof(code), stdin);
|
|
|
|
if (code[strlen(code) - 1] == '\n') {
|
|
code[strlen(code) - 1] = '\0';
|
|
}
|
|
|
|
printf("Read: %s\n", code);
|
|
|
|
if (brackets(code)) {
|
|
printf("All brackets OK\n");
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|