usaa24/a1/program.c

72 lines
1.7 KiB
C
Raw Normal View History

2024-10-23 08:12:43 +00:00
#include <stdio.h>
#include <string.h>
int isOpening(char c) {
return c == '{' || c == '[' || c == '(' || c == '<';
}
int isClosing(char c) {
return c == '}' || c == ']' || c == ')' || c == '>';
}
int isMatching(char open, char close) {
return (open == '{' && close == '}') ||
(open == '[' && close == ']') ||
(open == '(' && close == ')') ||
(open == '<' && close == '>');
}
2024-10-24 20:37:59 +00:00
char expectedClosing(char open) {
if (open == '{') return '}';
if (open == '[') return ']';
if (open == '(') return ')';
if (open == '<') return '>';
return '\0';
}
2024-10-23 08:12:43 +00:00
int main() {
char input[101];
char stack[100];
int top = -1;
fgets(input, 101, stdin);
2024-10-24 20:18:29 +00:00
printf("Read: %s", input);
2024-10-23 08:12:43 +00:00
for (int i = 0; i < strlen(input); i++) {
char current = input[i];
if (isOpening(current)) {
if (top < 99) {
stack[++top] = current;
} else {
2024-10-23 08:17:06 +00:00
printf("Stack is full\n");
2024-10-23 08:12:43 +00:00
return 1;
}
} else if (isClosing(current)) {
if (top == -1) {
2024-10-24 20:45:24 +00:00
printf("Unexpected closing bracket %c in %d\n", current, i);
2024-10-24 20:24:01 +00:00
return 0;
2024-10-23 08:12:43 +00:00
}
if (!isMatching(stack[top], current)) {
2024-10-24 20:43:13 +00:00
char expected = expectedClosing(stack[top]);
2024-10-24 20:48:19 +00:00
printf("Crossed bracket %c in %d, expected %c \n", current, i, expected);
2024-10-24 20:22:30 +00:00
return 0;
2024-10-23 08:12:43 +00:00
}
top--;
}
}
2024-10-24 20:43:13 +00:00
if (top != -1) {
printf("Missing closing brackets: ");
while (top != -1) {
printf("%c", expectedClosing(stack[top--]));
}
printf("\n");
2024-10-24 20:39:07 +00:00
return 0;
2024-10-23 08:12:43 +00:00
}
2024-10-23 08:13:45 +00:00
printf("All brackets OK\n");
2024-10-23 08:12:43 +00:00
return 0;
}