1
This commit is contained in:
parent
55a31d0896
commit
5405000c08
68
a1/program.c
Normal file
68
a1/program.c
Normal file
@ -0,0 +1,68 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define MAX_LEN 100
|
||||
|
||||
char pairs[][2] = {
|
||||
{'(', ')'},
|
||||
{'[', ']'},
|
||||
{'{', '}'},
|
||||
{'<', '>'}
|
||||
};
|
||||
|
||||
int is_open(char c) {
|
||||
for (int i = 0; i < 4; i++)
|
||||
if (pairs[i][0] == c) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int is_close(char c) {
|
||||
for (int i = 0; i < 4; i++)
|
||||
if (pairs[i][1] == c) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
char match(char c) {
|
||||
for (int i = 0; i < 4; i++)
|
||||
if (pairs[i][0] == c) return pairs[i][1];
|
||||
return '?';
|
||||
}
|
||||
|
||||
|
||||
int main(void) {
|
||||
char code[MAX_LEN + 2];
|
||||
char stack[MAX_LEN];
|
||||
int top = -1;
|
||||
|
||||
if (fgets(code, sizeof(code), stdin) == NULL)
|
||||
return 0;
|
||||
|
||||
|
||||
code[strcspn(code, "\n")] = '\0';
|
||||
|
||||
printf("Read: %s\n", code);
|
||||
|
||||
for (int i = 0; code[i] != '\0'; i++) {
|
||||
char c = code[i];
|
||||
|
||||
if (is_open(c)) {
|
||||
if (top < MAX_LEN - 1)
|
||||
stack[++top] = c;
|
||||
} else if (is_close(c)) {
|
||||
if (top < 0) {
|
||||
printf("Unexpected closing bracket %c in %d\n", c, i);
|
||||
return 0;
|
||||
}
|
||||
char last = stack[top--];
|
||||
if (match(last) != c)
|
||||
(void)(printf("Crossed bracket %c in %d, expected %c\n", c, i , match(last)), exit(0));
|
||||
}
|
||||
}
|
||||
|
||||
(top >= 0)
|
||||
? printf("Unclosed bracket %c in %d\n", stack[top], (int)strlen(code))
|
||||
: printf("All brackets OK\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user