try other

This commit is contained in:
Nataliia Kobryn 2025-10-20 19:59:56 +02:00
parent a4d2f90f18
commit 8890bbf80f
2 changed files with 47 additions and 78 deletions

BIN
a1/prog

Binary file not shown.

View File

@ -4,49 +4,6 @@
#define MAX_SIZE 1000
int 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 == '{' || c == '<') {
if (top < MAX_SIZE - 1) {
stack[++top] = c;
} else {
*err = i +1;
return 0;
}
}
else if (c == ')' || c == ']' || c == '}' || c == '>') {
if (top == -1) {
*err = i +1;
return 0;
}
char last = stack[top--];
if ((c == ')' && last != '(') ||
(c == ']' && last != '[') ||
(c == '}' && last != '{') ||
(c == '>' && last != '<')) {
*err = i+1;
return 0;
}
}
}
if (top != -1) {
// Знаходимо позицію незакритої дужки
char lastOpen = stack[top];
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] == lastOpen) {
*err = i +1;
return 0;
}
}
}
return 1;
}
char getExpectedClosing(char open) {
switch (open) {
case '(': return ')';
@ -56,47 +13,59 @@ char getExpectedClosing(char open) {
default: return '?';
}
}
bool isOpening(char c) {
return c == '(' || c == '[' || c == '{' || c == '<';
}
bool isClosing(char c) {
return c == ')' || c == ']' || c == '}' || c == '>';
}
char getExpectedOpening(char close) {
switch (close) {
case ')': return '(';
case ']': return '[';
case '}': return '{';
case '>': return '<';
default: return '?';
}
}
int main() {
char input[MAX_SIZE];
if (fgets(input, MAX_SIZE, stdin) != NULL) {
input[strcspn(input, "\n")] = '\0';
printf("Read: %s\n", input);
int err = 0;
if (is_valid_brackets(input, &err)) {
printf("All brackets OK\n");
} else {
char stack[MAX_SIZE];
int top = -1;
for (int i = 0; i < err; i++) {
for (int i = 0; input[i] != '\0'; i++) {
char c = input[i];
if (c == '(' || c == '[' || c == '{' || c == '<') {
if (isOpening(c)) {
stack[++top] = c;
} else if (c == ')' || c == ']' || c == '}' || c == '>') {
if (top >= 0 && c == getExpectedClosing(stack[top])) {
top--;
} else {
printf("Crossed bracket %c in %d, expected %c\n",
c, err, (top >= 0) ? getExpectedClosing(stack[top]) : '?');
} else if (isClosing(c)) {
if (top == -1) {
printf("Unexpected closing bracket %c in %d\n", c, i);
return 0;
}
char last = stack[top--];
if (getExpectedClosing(last) != c) {
printf("Crossed bracket %c in %d, expected %c \n", c, i , getExpectedClosing(last));
return 0;
}
}
}
char c = input[err - 1];
if (c == ')' || c == ']' || c == '}' || c == '>') {
if (top < -1) {
printf("Unexpected closing bracket %c in %d\n", c, err);
}
} else {
if (top != -1) {
printf("Missing closing brackets: ");
for (int i = top; i > -1; i--) {
for (int i = top; i >= 0; i--) {
printf("%c", getExpectedClosing(stack[i]));
}
printf("\n");
}
} else {
printf("All brackets OK\n");
}
} else {
printf("Error reading input\n");