usaa24/a1/program.c

70 lines
1.9 KiB
C
Raw 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 == '>');
}
void check_brackets(const char *code) {
char stack[MAX_LEN];
int positions[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;
positions[top] = i;
} 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)) {
printf("Crossed bracket %c in %d, expected %c\n", ch, i,
stack[top] == '(' ? ')' :
stack[top] == '{' ? '}' :
stack[top] == '[' ? ']' : '>');
return;
}
2024-10-29 13:56:05 +00:00
top--;
2024-10-29 13:47:48 +00:00
}
}
if (top != -1) {
printf("Unmatched opening bracket %c at position %d, expected %c\n",
stack[top], positions[top],
stack[top] == '(' ? ')' :
stack[top] == '{' ? '}' :
stack[top] == '[' ? ']' : '>');
} 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