스택 하면 딱 떠오르는 문제... 괄호 짝 맞추기
아래와 같이 간소하게? 스택을 구현해서 풀었다.
# include <stdio.h>
# define STACK_SIZE 50
typedef struct stack_ {
char items[STACK_SIZE];
size_t top;
} stack;
void s_init(stack *s) {
s->top = 0;
}
int is_empty_stack(stack *s) {
return s->top == 0;
}
void s_push(stack *s, char data) {
s->items[s->top++] = data;
}
void s_pop(stack *s) {
s->top--;
}
int main(void) {
int T;
scanf("%d", &T);
for (int i = 0;i < T;i++) {
char input[51];
scanf(" %s", input);
stack s;
s_init(&s);
int k = 0;
int mismatch = 0;
while (input[k]) {
if (input[k] == '(') s_push(&s, input[k]);
else if (input[k] == ')') {
if (is_empty_stack(&s)) {
printf("NO\n");
mismatch = 1;
break;
}
else {
s_pop(&s);
}
}
k++;
}
if (is_empty_stack(&s) && !mismatch) printf("YES\n");
else if (!is_empty_stack(&s)) printf("NO\n"); // !! important !!
}
return 0;
}