usaa24/a1/program.c

71 lines
1.7 KiB
C
Raw Permalink Normal View History

2024-10-29 13:47:48 +00:00
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int is_matching_pair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']') ||
(open == '<' && close == '>');
}
2024-10-29 14:09:54 +00:00
char matching_close(char open) {
return open == '(' ? ')' :
open == '{' ? '}' :
open == '[' ? ']' : '>';
}
2024-10-29 13:47:48 +00:00
void check_brackets(const char *code) {
char stack[MAX_LEN];
2024-10-29 13:56:05 +00:00
int top = -1;
2024-10-29 13:47:48 +00:00
printf("Read: %s\n", code);
for (int i = 0; i < strlen(code); i++) {
char ch = code[i];
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
if (top < MAX_LEN - 1) {
stack[++top] = ch;
} else {
printf("Stack overflow at position %d\n", i);
return;
}
}
else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') {
if (top == -1) {
2024-10-29 14:01:24 +00:00
printf("Unexpected closing bracket %c in %d\n", ch, i);
2024-10-29 13:47:48 +00:00
return;
}
if (!is_matching_pair(stack[top], ch)) {
2024-10-29 14:13:08 +00:00
printf("Crossed bracket %c in %d, expected %c \n", ch, i, matching_close(stack[top]));
2024-10-29 13:47:48 +00:00
return;
}
2024-10-29 13:56:05 +00:00
top--;
2024-10-29 13:47:48 +00:00
}
}
if (top != -1) {
2024-10-29 14:09:54 +00:00
printf("Missing closing brackets: ");
while (top != -1) {
printf("%c", matching_close(stack[top--]));
}
printf("\n");
2024-10-29 13:47:48 +00:00
} else {
printf("All brackets OK\n");
}
}
2024-10-29 13:49:40 +00:00
int main() {
2024-10-29 13:56:05 +00:00
char code[MAX_LEN];
if (fgets(code, MAX_LEN, stdin) != NULL) {
code[strcspn(code, "\n")] = '\0';
check_brackets(code);
}
2024-10-29 13:49:40 +00:00
return 0;
2024-10-29 14:04:34 +00:00
}
2024-10-29 13:56:05 +00:00