a1 - 1
This commit is contained in:
parent
52e63a3d03
commit
b2a8ce914d
76
a1/program.c
Normal file
76
a1/program.c
Normal file
@ -0,0 +1,76 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_LEN 100
|
||||
|
||||
int isOpening(char c){
|
||||
if (c == '(' || c == '[' || c == '{' || c == '<') return 1
|
||||
}
|
||||
|
||||
int isClosing(char c){
|
||||
if (c == ')' || c == ']' || c == '}' || c == '>') return 1
|
||||
}
|
||||
|
||||
char expectedCLosing(char c){
|
||||
switch (c) {
|
||||
case '(': return ')';
|
||||
case '[': return ']';
|
||||
case '{': return '}';
|
||||
case '<': return '>';
|
||||
default: return '?';
|
||||
}
|
||||
}
|
||||
|
||||
char expectedOpening(char c){
|
||||
switch (c) {
|
||||
case ')': return '(';
|
||||
case ']': return '[';
|
||||
case '}': return '{';
|
||||
case '>': return '<';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main(){
|
||||
char code[MAX_LEN + 1];
|
||||
char stack[MAX_LEN];
|
||||
int top = -1;
|
||||
|
||||
if (!fgets(code, sizeof(code), stdin)){
|
||||
printf("Input error\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
code[strcspn(code, "\n")] = '\0';
|
||||
|
||||
printf("Read: %s\n", code);
|
||||
|
||||
int len = strlen(code);
|
||||
for (int i = 0; i < len; i++){
|
||||
c = code[i];
|
||||
|
||||
if (isOpening(c)){
|
||||
if (top < MAX_LEN - 1){
|
||||
stack[++top] = c;
|
||||
}
|
||||
}
|
||||
else if (isClosing(c)){
|
||||
if (top < 0){
|
||||
printf("Unexpected closing bracket %c in %d\n", c, i+1);
|
||||
return 0;
|
||||
}
|
||||
char last = stack[top--];
|
||||
if (expectedClosing(last) != c){
|
||||
printf("Crossed bracket %c in %d, expected %c\n", c, i+1, expectedClosing(last));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (top >= 0){
|
||||
printf("Unclosed bracket %c in %d\n", stack[top], len);
|
||||
} else {
|
||||
printf("All brackets OK\n");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user