usaa24/a1/program.c

73 lines
1.8 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;
2024-10-24 20:18:29 +00:00
// printf("");
2024-10-23 08:12:43 +00:00
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:26:12 +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:18:29 +00:00
printf("Crossed bracket '%c' in %d , expected \n", current, i);
2024-10-23 08:12:43 +00:00
(stack[top] == '{') ? '}' :
(stack[top] == '[') ? ']' :
(stack[top] == '(') ? ')' : '>',
2024-10-24 20:18:29 +00:00
current, i;
2024-10-24 20:22:30 +00:00
return 0;
2024-10-23 08:12:43 +00:00
}
top--;
}
}
2024-10-24 20:33:03 +00:00
if (top != -1) {
2024-10-24 20:37:59 +00:00
char expected = expectedClosing(stack[top]);
printf("Missing closing brackets: %c\n", expected);
return 1;
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;
}