<<<<attempt1>>>>
#include<stdio.h>
#include<string.h>
//():0 []:1
int main(){
int stack[105];
int top = 0;
char string[105];
while(1){
fgets(string,105,stdin);
if(string[0]=='.'&&string[1]=='\n')
return 0;
for(int i=0;string[i]!='\0';i++){
if(string[i]=='\n'){
if(top==0)
printf("yes\n");
else
printf("no\n");
top=0;
}
else if(string[i]=='(')
stack[top++] = 0;
else if(string[i]=='[')
stack[top++] = 1;
else if(string[i]==')'){
if(stack[top-1]==0)//////////*************top=0인 경우에 stack[-1]에 접근할 수 없으므로 틀림.
top--;
else{
printf("no\n");
top = 0;
break;
}
}
else if(string[i]==']'){
if(stack[top-1]==1)//////////*************top=0인 경우에 stack[-1]에 접근할 수 없으므로 틀림.
top--;
else{
printf("no\n");
top = 0;
break;
}
}
}
}
return 0;
}
----------------------------------------------------------------------------------------------------------------------------------------
반례를 찾으려고 하기 보다는 내 코드에 어떠한 문제가 발생할 수 있는지 기본적인것부터 확인해보자.
***배열의 경우에는 범위를 벗어나는 경우가 빈번히 발생하므로 이를 주의하도록 하자!!!
----------------------------------------------------------------------------------------------------------------------------------------
<<<<수정코드>>>>
#include<stdio.h>
#include<string.h>
//():0 []:1
int main(){
int stack[105] = {-1,};
int top = 0;
char string[105];
while(1){
fgets(string,105,stdin);
if(string[0]=='.'&&string[1]=='\n')
return 0;
for(int i=0;string[i]!='\0';i++){
if(string[i]=='\n'){
if(top==0)
printf("yes\n");
else
printf("no\n");
top=0;
break;
}
else if(string[i]=='(')
stack[top++] = 0;
else if(string[i]=='[')
stack[top++] = 1;
else if(string[i]==')'){
if(top>0){
if(stack[top-1]==0)
top--;
else{
printf("no\n");
top = 0;
break;
}
}
else{
printf("no\n");
top = 0;
break;
}
}
else if(string[i]==']'){
if(top>0){
if(stack[top-1]==1)
top--;
else{
printf("no\n");
top = 0;
break;
}
}
else{
printf("no\n");
top = 0;
break;
}
}
}
}
return 0;
}
'프로그래밍 > C' 카테고리의 다른 글
baekjoon 10828.c 스택구현 w/structure pointer (0) | 2022.01.30 |
---|---|
baekjoon 1107 w/ dfs 나중에 다시 풀어볼만한 문제(0ms에 도전) (0) | 2022.01.23 |
baekjoon 1929 소수구하기 // 시간초과 & 에라토스테네스의 체 (0) | 2022.01.22 |
baekjoon 10816 attempt 1 & why it is wrong & 수정 코드 (0) | 2022.01.18 |
baekjoon10814 //using 전역변수 (0) | 2022.01.17 |