check
This commit is contained in:
parent
63d552bb53
commit
6c76f47cde
60
a1/program.c
Normal file
60
a1/program.c
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#define MAX_SIZE 1000
|
||||||
|
|
||||||
|
bool is_valid_brackets(const char* s, int* err) {
|
||||||
|
char stack[MAX_SIZE];
|
||||||
|
int top = -1;
|
||||||
|
|
||||||
|
for (int i = 0; s[i] != '\0'; i++) {
|
||||||
|
char c = s[i];
|
||||||
|
if (c == '(' || c == '[' || c == '{') {
|
||||||
|
if (top < MAX_SIZE - 1) {
|
||||||
|
stack[++top] = c;
|
||||||
|
} else {
|
||||||
|
*err= i + 1;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (c == ')' || c == ']' || c == '}') {
|
||||||
|
if (top == -1) {
|
||||||
|
*err= i + 1;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
char last = stack[top--];
|
||||||
|
if ((c == ')' && last != '(') ||
|
||||||
|
(c == ']' && last != '[') ||
|
||||||
|
(c == '}' && last != '{')) {
|
||||||
|
*err
|
||||||
|
= i + 1;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (top != -1) {
|
||||||
|
*err = strlen(s) + 1;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
char input[MAX_SIZE];
|
||||||
|
|
||||||
|
if (fgets(input, MAX_SIZE, stdin) != NULL) {
|
||||||
|
input[strcspn(input, "\n")] = '\0';
|
||||||
|
|
||||||
|
int err = 0;
|
||||||
|
if (is_valid_brackets(input, &err)) {
|
||||||
|
printf("True\n");
|
||||||
|
} else {
|
||||||
|
printf("False at position %d\n", err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user