73 lines
1.8 KiB
C
73 lines
1.8 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;
|
|
|
|
// printf("");
|
|
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)) {
|
|
printf("Crossed bracket '%c' in %d , expected \n", current, i);
|
|
(stack[top] == '{') ? '}' :
|
|
(stack[top] == '[') ? ']' :
|
|
(stack[top] == '(') ? ')' : '>',
|
|
current, i;
|
|
return 0;
|
|
}
|
|
top--;
|
|
}
|
|
}
|
|
|
|
if (top != -1) {
|
|
char expected = expectedClosing(stack[top]);
|
|
printf("Missing closing brackets: %c\n", expected);
|
|
return 0;
|
|
}
|
|
|
|
printf("All brackets OK\n");
|
|
return 0;
|
|
}
|