4949번. 균형잡힌 세상_다시 풀자. 240320

phoenixKim·2022년 9월 4일
0

백준 알고리즘

목록 보기
103/174

풀이전략 : 최근 풀이.

    1. stack 없이 진행하려고 했다.
      소문자는 num1 , 대문자는 num2로 진행하려고 했는데 .
  • 연속되는 소괄호 close는 바로 앞단에 소괄호 open이 와야하니까.
    여기서 stack을 사용해야 겠다 생각함.

    1. for문 진행중에 break; 처리할 때 빠져나온 코드 뒤에 출력을 하고 있기 때문에 반드시 bool check 변수가 필요하다.
      : break; 문으로 빠져나오더라도 밑에 출력 코드가 있다.
      여기에 진입을 못하게 해야 한다.

반례 가장 중요!

  • 중요한 점은 반례에 대해서 생각해야 한다.
    ]] 가 올수도 있고,
    [[[[[]] 가 올수도 있다.
    이를 생각하면서 조건 처리를 생각해야 함.

코드

#include <iostream>
#include <list>
using namespace std;
#include <map>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>

// 4949 균형 잡힌 세상.
// 15:22 ~ 15:45

int main()
{
	
	// 소괄호 변수
	// 대괄호 변수 
	// 만들어서 카운팅을 진행함. 


	while (1)
	{
		string s;
		//cin >> s;
		getline(cin, s);

		if (s[0] == '.')
		{
			return 0;
		}

		// 풀이전략 변경함.  : 15:41 ~ 15:45
		stack<char>sta;

		int soCnt = 0;
		int daeCnt = 0;
		bool check = false;
		for (auto iter : s)
		{
			if (iter == '(')
			{
				++soCnt;
				sta.push('(');
			}
			else if (iter == ')')
			{
				--soCnt;


				if (!sta.empty())
				{
					if (sta.top() == '(')
					{
						sta.pop();
					}
					else
					{
						check = true;
						cout << "no" << endl;
						break;
					}
				}
				
			}
			else if (iter == '[')
			{
				++daeCnt;
				sta.push('[');

			}
			else if (iter == ']')
			{
				--daeCnt;

				if (!sta.empty())
				{
					if (sta.top() == '[')
					{
						sta.pop();
					}
					else
					{
						check = true;
						cout << "no" << endl;
						break;
					}
				}
				
			}

			if (soCnt < 0 || daeCnt < 0)
			{
				cout << "no" << endl;
				check = true;
				break;
			}

			// 짝짝이 일 경우에 no 출력해야 함.
			// 5번째 예제 해당함.

		}

		if (check == false)
		{
			if (soCnt == 0 && daeCnt == 0)
			{
				cout << "yes" << endl;
			}
			else
			{
				cout << "no" << endl;
			}
		}
		


	}


	
}

profile
🔥🔥🔥

0개의 댓글

관련 채용 정보