usaa24/a1/program.c

72 lines
1.7 KiB
C

#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 == '>');
}
char expectedClosing(char open) {
if (open == '{') return '}';
if (open == '[') return ']';
if (open == '(') return ')';
if (open == '<') return '>';
return '\0';
}
int main() {
char input[101];
char stack[100];
int top = -1;
fgets(input, 101, stdin);
printf("Read: %s", input);
for (int i = 0; i < strlen(input); i++) {
char current = input[i];
if (isOpening(current)) {
if (top < 99) {
stack[++top] = current;
} else {
printf("Stack is full\n");
return 1;
}
} else if (isClosing(current)) {
if (top == -1) {
printf("Unexpected closing bracket %c in %d\n", current, i);
return 0;
}
if (!isMatching(stack[top], current)) {
char expected = expectedClosing(stack[top]);
printf("Crossed bracket %c in %d, expected %c\n", current, i, expected);
return 0;
}
top--;
}
}
if (top != -1) {
printf("Missing closing brackets: ");
while (top != -1) {
printf("%c", expectedClosing(stack[top--]));
}
printf("\n");
return 0;
}
printf("All brackets OK\n");
return 0;
}