[C언어] 백준 4949 : 균형잡힌 세상

mainsain·2022년 3월 30일
0

백준

목록 보기
60/64


이전 문제처럼 걍 더하고 빼고 하면 될 줄알았는데, 예외케이스가 너무 많았다..
결국 내 코드를 갈아버리고, 스택을 사용하는 방법을 찾았다.
여기에 시간을 너무 많이 갈아버렸다. 심지어 거의 클론코딩수준이다.. 어떤식으로 돌아가는지 보고, 다음에 다시 한 번 풀어보도록 하자..

내가 푼 코드 (틀림)

#include <stdio.h>
int main()
{
	char str[101];
	int countA;
	int countB;
	while (1)
	{
		scanf("%[^\n]%*c", str);
		int i = 0;
		countA = 0;
		countB = 0;
		if (str[0] == '.')
			return 0;
		while (str[i] != '\0')
		{
			if (str[i] == '(')
				countA++;
			if (str[i] == ')')
				countA--;
			if (str[i] == '[')
				countB++;
			if (str[i] == ']')
				countB--;
			if (countA < 0 || countB < 0)
			{
				printf("no\n");
				break;
			}
			i++;
		}
		if (countA == 0 && countB == 0)
			printf("yes\n");
		else if (countA > 0 || countB > 0)
			printf("no\n");
	}
}

다른 사람 코드

#include <stdio.h>
#include <string.h>
#define MAX 100
 
char stack[MAX];
int top = -1;
 
//스택에 데이터를 집어넣는다.
int push(char ch) {
    if (top >= MAX - 1) return -1;
    return stack[++top] = ch;
}
 
//스택에서 데이터를 뽑는다.
int pop() {
    if (top < 0) return -1;
    return stack[top--] = '\0';
}
 
//스택 상단의 내용을 읽는다.
char peek() {
    return stack[top];
}
 
//균형잡힌 문자열인지를 판단
void Result(char *ch, int size) {
    for (int i = 0; i < size; i++) {
        if (ch[i] == '(' || ch[i] == ')' || ch[i] == '[' || ch[i] == ']') {
            //top가 -1이라면 무조건 push
            if (top == -1) push(ch[i]);
            else {
                //짝이라면 pop
                if (peek() == '('&&ch[i] == ')') pop();
                else if (peek() == '['&&ch[i] == ']') pop();
                //그 외 push
                else push(ch[i]);
            }
        }
    }
    //top가 -1이면 균형잡힌 문자열
    if (top == -1) printf("yes\n");
    else printf("no\n");
}
 
int main() {
    char str[MAX];
    while (1) {
        top = -1;
        gets(str);
        if (strcmp(str, ".") == 0) break;
        Result(str, strlen(str));
    }
    return 0;
}

https://wtg-study.tistory.com/16

다음에 다시보자

profile
새로운 자극을 주세요.

0개의 댓글