BUPT-homework/semester3/pset1/7-1-Balancing-Symbols.c
2022-10-14 18:47:09 +08:00

94 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
int parenToInt(char ch) {
if (ch == '(') {
return 0;
} else if (ch == ')') {
return 1;
} else if (ch == '[') {
return 2;
} else if (ch == ']') {
return 3;
} else if (ch == '{') {
return 4;
} else if (ch == '}') {
return 5;
} else {
return -1;
}
}
typedef struct stack {
int top;
int capacity;
int *array;
} stack;
stack *newStack(int capacity) {
stack *st = malloc(sizeof(stack));
st->capacity = 50;
st->top = -1;
st->array = malloc(st->capacity * sizeof(int));
return st;
}
void push(stack *st, int val) {
st->top++;
st->array[st->top] = val;
}
int peek(stack *st) { return st->array[st->top]; }
void pop(stack *st) { st->top--; }
int isEmpty(stack *st) { return (st->top == -1); }
int main(void) {
char input[SIZE];
fgets(input, SIZE, stdin);
int num;
int ans[3] = {};
stack *st = newStack(SIZE);
for (int i = 0; input[i] != '\0'; i++) {
num = parenToInt(input[i]);
if (num != -1) {
if (num % 2 == 0) {
// left paren , push to stack
push(st, num);
} else {
// right paren
if (!isEmpty(st) && peek(st) == num - 1) {
pop(st);
} else {
// a error
ans[num / 2] = 1;
}
}
}
}
while (!isEmpty(st)) {
num = peek(st);
ans[num / 2] = 1;
pop(st);
}
int incorrect = ans[0] | ans[1] | ans[2];
if (incorrect) {
for (int i = 0; i < 3; i++) {
if (ans[i]) {
printf("%d,", i + 1);
}
}
} else {
printf("0");
}
return 0;
}