a1
This commit is contained in:
parent
a05d096bb4
commit
104b94822f
73
a1/program.c
Normal file
73
a1/program.c
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#define MAX 101
|
||||||
|
|
||||||
|
// funkcia, ktorá vracia zodpovedajúcu zatváraciu zátvorku
|
||||||
|
char expected_close(char open) {
|
||||||
|
switch (open) {
|
||||||
|
case '(': return ')';
|
||||||
|
case '{': return '}';
|
||||||
|
case '[': return ']';
|
||||||
|
case '<': return '>';
|
||||||
|
default: return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
char line[MAX];
|
||||||
|
char stack[MAX];
|
||||||
|
int pos[MAX]; // pozície otvorených zátvoriek
|
||||||
|
int top = -1; // index vrcholu zásobníka
|
||||||
|
|
||||||
|
// načítanie jedného riadku
|
||||||
|
if (fgets(line, MAX, stdin) == NULL)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
// odstrániť znak nového riadku, ak je prítomný
|
||||||
|
line[strcspn(line, "\n")] = '\0';
|
||||||
|
|
||||||
|
printf("Read: %s\n", line);
|
||||||
|
|
||||||
|
int ok = 1;
|
||||||
|
int length = strlen(line);
|
||||||
|
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
char ch = line[i];
|
||||||
|
|
||||||
|
// ak je otváracia zátvorka
|
||||||
|
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
|
||||||
|
top++;
|
||||||
|
stack[top] = ch;
|
||||||
|
pos[top] = i + 1; // indexovanie od 1
|
||||||
|
}
|
||||||
|
// ak je zatváracia zátvorka
|
||||||
|
else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') {
|
||||||
|
if (top < 0) {
|
||||||
|
printf("Unexpected closing bracket %c in %d\n", ch, i + 1);
|
||||||
|
ok = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
char last_open = stack[top];
|
||||||
|
char expected = expected_close(last_open);
|
||||||
|
if (ch != expected) {
|
||||||
|
printf("Crossed bracket %c in %d, expected %c\n", ch, i + 1, expected);
|
||||||
|
ok = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
top--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ok && top >= 0) {
|
||||||
|
printf("Missing closing bracket for %c from %d\n", stack[top], pos[top]);
|
||||||
|
ok = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ok)
|
||||||
|
printf("All brackets OK\n");
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user