usaa24/a1/program.c

63 lines
1.6 KiB
C
Raw Permalink Normal View History

2024-10-31 18:45:11 +00:00
#include <stdio.h>
2024-10-31 18:46:23 +00:00
#include <string.h>
2024-10-31 18:45:11 +00:00
int match(char open, char close) {
2024-10-31 19:02:33 +00:00
return (open == '{' && close == '}') || (open == '[' && close == ']') ||
2024-10-31 22:31:56 +00:00
(open == '(' && close == ')') || (open == '<' && close == '>');
2024-10-31 18:45:11 +00:00
}
2024-10-31 23:00:05 +00:00
char expected_closing(char open) {
if (open == '{') return '}';
if (open == '[') return ']';
if (open == '(') return ')';
if (open == '<') return '>';
return '\0';
}
2024-10-31 18:45:11 +00:00
void check_brackets(const char *code) {
char stack[100];
2024-10-31 18:46:23 +00:00
int top = -1;
2024-10-31 18:45:11 +00:00
2024-10-31 23:00:05 +00:00
printf("Read: %s\n", code);
2024-10-31 18:45:11 +00:00
2024-10-31 18:46:23 +00:00
for (int i = 0; code[i] != '\0'; i++) {
2024-10-31 18:45:11 +00:00
char c = code[i];
2024-10-31 22:31:56 +00:00
if (c == '{' || c == '[' || c == '(' || c == '<') {
2024-10-31 19:02:33 +00:00
stack[++top] = c;
2024-10-31 22:31:56 +00:00
} else if (c == '}' || c == ']' || c == ')' || c == '>') {
2024-10-31 19:02:33 +00:00
if (top == -1) {
2024-10-31 22:48:30 +00:00
printf("Unexpected closing bracket %c in %d\n", c, i);
2024-10-31 19:02:33 +00:00
return;
2024-10-31 18:46:23 +00:00
}
2024-10-31 19:02:33 +00:00
if (!match(stack[top], c)) {
2024-10-31 23:01:43 +00:00
printf("Crossed bracket %c in %d, expected %c \n", c, i, expected_closing(stack[top]));
2024-10-31 18:45:11 +00:00
return;
}
2024-10-31 18:46:23 +00:00
top--;
2024-10-31 18:45:11 +00:00
}
}
2024-10-31 23:00:05 +00:00
2024-10-31 18:46:23 +00:00
if (top == -1) {
2024-10-31 22:26:55 +00:00
printf("All brackets OK\n");
2024-10-31 18:46:23 +00:00
} else {
2024-10-31 22:57:00 +00:00
printf("Missing closing brackets: ");
while (top >= 0) {
2024-10-31 23:00:05 +00:00
printf("%c", expected_closing(stack[top--]));
2024-10-31 22:57:00 +00:00
}
printf("\n");
2024-10-31 18:46:23 +00:00
}
2024-10-31 18:45:11 +00:00
}
int main() {
char code[100];
2024-10-31 22:42:43 +00:00
if (fgets(code, sizeof(code), stdin) != NULL) {
2024-10-31 22:48:30 +00:00
2024-10-31 22:45:27 +00:00
size_t len = strlen(code);
if (len > 0 && code[len - 1] == '\n') {
code[len - 1] = '\0';
}
2024-10-31 22:42:43 +00:00
check_brackets(code);
}
2024-10-31 18:45:11 +00:00
return 0;
2024-10-31 19:02:33 +00:00
}