2024-10-29 13:29:22 +00:00
|
|
|
#include <stdio.h>
|
2024-10-29 16:46:23 +00:00
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
#define MAX_LEN 101
|
|
|
|
|
|
|
|
typedef struct {
|
|
|
|
char bracket;
|
|
|
|
int position;
|
|
|
|
} StackItem;
|
|
|
|
|
|
|
|
int is_opening(char ch) {
|
|
|
|
return ch == '(' || ch == '{' || ch == '[' || ch == '<';
|
|
|
|
}
|
|
|
|
|
|
|
|
int is_closing(char ch) {
|
|
|
|
return ch == ')' || ch == '}' || ch == ']' || ch == '>';
|
|
|
|
}
|
|
|
|
|
|
|
|
char matching_bracket(char ch) {
|
|
|
|
switch (ch) {
|
|
|
|
case ')': return '(';
|
|
|
|
case '}': return '{';
|
|
|
|
case ']': return '[';
|
|
|
|
case '>': return '<';
|
|
|
|
default: return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-29 16:55:12 +00:00
|
|
|
char expected_closing(char ch) {
|
|
|
|
switch (ch) {
|
|
|
|
case '(': return ')';
|
|
|
|
case '{': return '}';
|
|
|
|
case '[': return ']';
|
|
|
|
case '<': return '>';
|
|
|
|
default: return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-29 16:46:23 +00:00
|
|
|
void check_brackets(const char *line) {
|
|
|
|
StackItem stack[MAX_LEN];
|
|
|
|
int stack_top = -1;
|
|
|
|
|
|
|
|
printf("Read: %s\n", line);
|
|
|
|
|
|
|
|
for (int i = 0; line[i] != '\0'; i++) {
|
|
|
|
char ch = line[i];
|
|
|
|
|
|
|
|
if (is_opening(ch)) {
|
|
|
|
if (stack_top < MAX_LEN - 1) {
|
|
|
|
stack[++stack_top].bracket = ch;
|
|
|
|
stack[stack_top].position = i;
|
|
|
|
} else {
|
|
|
|
printf("Error: Stack overflow\n");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
} else if (is_closing(ch)) {
|
2024-10-29 16:51:58 +00:00
|
|
|
if (stack_top == -1) {
|
2024-10-29 17:01:15 +00:00
|
|
|
printf("Unexpected closing bracket %c in %d \n", ch, i);
|
2024-10-29 16:51:58 +00:00
|
|
|
return;
|
|
|
|
} else if (stack[stack_top].bracket == matching_bracket(ch)) {
|
2024-10-29 16:46:23 +00:00
|
|
|
stack_top--;
|
|
|
|
} else {
|
2024-10-29 17:01:15 +00:00
|
|
|
printf("Crossed bracket %c in %d, expected %c \n", ch, i,
|
2024-10-29 16:55:12 +00:00
|
|
|
expected_closing(stack[stack_top].bracket));
|
2024-10-29 16:46:23 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (stack_top >= 0) {
|
2024-10-29 16:55:12 +00:00
|
|
|
printf("Missing closing brackets:");
|
2024-10-29 16:58:51 +00:00
|
|
|
printf(" ");
|
|
|
|
while (stack_top >= 0) {
|
|
|
|
printf("%c", expected_closing(stack[stack_top].bracket));
|
2024-10-29 16:55:12 +00:00
|
|
|
stack_top--;
|
|
|
|
}
|
|
|
|
printf("\n");
|
2024-10-29 16:46:23 +00:00
|
|
|
} else {
|
|
|
|
printf("All brackets OK\n");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
char line[MAX_LEN];
|
|
|
|
if (fgets(line, sizeof(line), stdin)) {
|
|
|
|
line[strcspn(line, "\n")] = '\0';
|
|
|
|
check_brackets(line);
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|