66 lines
1.8 KiB
C
66 lines
1.8 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
#define MAX 100
|
|
|
|
// Pomocná funkcia na kontrolu páru zátvoriek
|
|
int is_matching_pair(char open, char close) {
|
|
return (open == '(' && close == ')') ||
|
|
(open == '{' && close == '}') ||
|
|
(open == '[' && close == ']') ||
|
|
(open == '<' && close == '>');
|
|
}
|
|
|
|
// Funkcia na kontrolu správnosti zátvoriek
|
|
void check_brackets(const char *code) {
|
|
char stack[MAX];
|
|
int stack_top = -1; // vrchol zásobníka
|
|
|
|
printf("Read: %s\n", code);
|
|
|
|
for (int i = 0; code[i] != '\0'; i++) {
|
|
char c = code[i];
|
|
|
|
// Ak je znak otváracia zátvorka, pridaj ho na zásobník
|
|
if (c == '(' || c == '{' || c == '[' || c == '<') {
|
|
if (stack_top >= MAX - 1) {
|
|
printf("Stack overflow at position %d\n", i);
|
|
return;
|
|
}
|
|
stack[++stack_top] = c;
|
|
}
|
|
// Ak je znak zatváracia zátvorka
|
|
else if (c == ')' || c == '}' || c == ']' || c == '>') {
|
|
if (stack_top < 0) {
|
|
printf("Unexpected closing bracket %c in %d\n", c, i);
|
|
return;
|
|
}
|
|
char top = stack[stack_top--];
|
|
if (!is_matching_pair(top, c)) {
|
|
printf("Crossed bracket %c in %d, expected %c\n", c, i, top);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Skontroluj, či sú všetky zátvorky uzavreté
|
|
if (stack_top >= 0) {
|
|
printf("Unmatched bracket at the end\n");
|
|
} else {
|
|
printf("All brackets OK\n");
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
char code[MAX];
|
|
|
|
fgets(code, MAX, stdin);
|
|
|
|
// Odstráň novoriadok na konci
|
|
code[strcspn(code, "\n")] = '\0';
|
|
|
|
// Skontroluj zátvorky
|
|
check_brackets(code);
|
|
|
|
return 0;
|
|
} |