2024-10-26 18:43:36 +00:00
|
|
|
#include <stdio.h>
|
2024-10-26 19:31:08 +00:00
|
|
|
#include <string.h>
|
|
|
|
|
2024-10-26 18:43:36 +00:00
|
|
|
#define MAX 100
|
|
|
|
|
2024-10-26 19:43:02 +00:00
|
|
|
// Функція для визначення очікуваної закриваючої дужки
|
|
|
|
char expected_close(char open) {
|
|
|
|
switch(open) {
|
|
|
|
case '(': return ')';
|
|
|
|
case '{': return '}';
|
|
|
|
case '[': return ']';
|
|
|
|
case '<': return '>';
|
|
|
|
default: return '\0';
|
|
|
|
}
|
2024-10-26 19:31:08 +00:00
|
|
|
}
|
|
|
|
|
2024-10-26 19:43:02 +00:00
|
|
|
// Функція для перевірки коректності дужок
|
2024-10-26 19:31:08 +00:00
|
|
|
void check_brackets(const char *code) {
|
|
|
|
char stack[MAX];
|
2024-10-26 19:43:02 +00:00
|
|
|
int stack_top = -1; // Вершина стеку
|
2024-10-26 19:31:08 +00:00
|
|
|
|
|
|
|
printf("Read: %s\n", code);
|
2024-10-26 19:20:18 +00:00
|
|
|
|
2024-10-26 19:31:08 +00:00
|
|
|
for (int i = 0; code[i] != '\0'; i++) {
|
|
|
|
char c = code[i];
|
|
|
|
|
2024-10-26 19:43:02 +00:00
|
|
|
// Якщо відкрита дужка, додаємо її до стеку
|
2024-10-26 19:31:08 +00:00
|
|
|
if (c == '(' || c == '{' || c == '[' || c == '<') {
|
|
|
|
if (stack_top >= MAX - 1) {
|
|
|
|
printf("Stack overflow at position %d\n", i);
|
|
|
|
return;
|
2024-10-26 19:20:18 +00:00
|
|
|
}
|
2024-10-26 19:31:08 +00:00
|
|
|
stack[++stack_top] = c;
|
2024-10-26 19:20:18 +00:00
|
|
|
}
|
2024-10-26 19:43:02 +00:00
|
|
|
// Якщо закрита дужка
|
2024-10-26 19:31:08 +00:00
|
|
|
else if (c == ')' || c == '}' || c == ']' || c == '>') {
|
|
|
|
if (stack_top < 0) {
|
2024-10-26 19:33:35 +00:00
|
|
|
printf("Unexpected closing bracket %c in %d\n", c, i);
|
2024-10-26 19:31:08 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
char top = stack[stack_top--];
|
2024-10-26 19:43:02 +00:00
|
|
|
char expected = expected_close(top);
|
|
|
|
if (expected != c) {
|
|
|
|
printf("Crossed bracket %c in %d, expected %c\n", c, i, expected);
|
2024-10-26 19:31:08 +00:00
|
|
|
return;
|
|
|
|
}
|
2024-10-26 19:20:18 +00:00
|
|
|
}
|
|
|
|
}
|
2024-10-26 19:26:38 +00:00
|
|
|
|
2024-10-26 19:43:02 +00:00
|
|
|
// Перевірка, чи всі дужки закриті
|
2024-10-26 19:31:08 +00:00
|
|
|
if (stack_top >= 0) {
|
2024-10-26 19:40:34 +00:00
|
|
|
printf("Missing closing bracket: %c\n", stack[stack_top]);
|
2024-10-26 19:31:08 +00:00
|
|
|
} else {
|
|
|
|
printf("All brackets OK\n");
|
|
|
|
}
|
2024-10-26 18:43:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
2024-10-26 19:31:08 +00:00
|
|
|
char code[MAX];
|
|
|
|
|
|
|
|
fgets(code, MAX, stdin);
|
|
|
|
|
2024-10-26 19:43:02 +00:00
|
|
|
// Видаляємо символ нової строки в кінці
|
2024-10-26 19:31:08 +00:00
|
|
|
code[strcspn(code, "\n")] = '\0';
|
|
|
|
|
2024-10-26 19:43:02 +00:00
|
|
|
// Перевірка дужок
|
2024-10-26 19:31:08 +00:00
|
|
|
check_brackets(code);
|
|
|
|
|
2024-10-26 18:43:36 +00:00
|
|
|
return 0;
|
2024-10-26 19:43:02 +00:00
|
|
|
}
|