Algorithm/백준

[백준] 4949 균형잡힌 세상 with C++

nowkoes 2023. 5. 11. 00:00

문제설명


입출력 예제


개념

 주어진 문자열에서 괄호만 추출해서 소괄호와 중괄호가 알맞게 짝을 이루고 있는지 확인하는 문제다. 괄호는 스택으로 처리하면 편하게 해결할 수 있지만, 문자열의 종료 시점을 정하는 게 까다로웠다. 필자는 문자열에서 온점을 찾고, 그 문자열의 크기가 1일 때를 종료 시점으로 정했다.


풀이

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{
	while (true)
	{
		string str;
		stack<char> st;
		getline(cin, str);

		if (str.find(".") != string::npos && str.size() == 1)
			break;

 문자열 str을 공백을 포함하여 입력받고, 종료 시점인지 판단한다.

 

		else if (str.find(".") != string::npos)
		{
			for (auto& value : str)
			{
				if (value == '(' || value == '[')
					st.push(value);

				else if (!st.empty() && (st.top() == '(' && value == ')'))
					st.pop();

				else if (!st.empty() && (st.top() == '[' && value == ']'))
					st.pop();

				else if (value == ']' || value == ')')
					st.push(value);
			}

			if (st.empty())
				cout << "yes\n";
			else
				cout << "no\n";
		}
	}
}

 종료 시점이 아닌 경우, 문자를 하나씩 받아 여는 괄호는 스택에 넣는다. 만약 닫는 괄호를 입력받았을 때 스택의 top이 (), 혹은 []으로 완성된다면 스택에서 꺼내준다.

 

총합본

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{
	while (true)
	{
		string str;
		stack<char> st;
		getline(cin, str);

		if (str.find(".") != string::npos && str.size() == 1)
			break;
		
		else if (str.find(".") != string::npos)
		{
			for (auto& value : str)
			{
				if (value == '(' || value == '[')
					st.push(value);

				else if (!st.empty() && (st.top() == '(' && value == ')'))
					st.pop();

				else if (!st.empty() && (st.top() == '[' && value == ']'))
					st.pop();

				else if (value == ']' || value == ')')
					st.push(value);
			}

			if (st.empty())
				cout << "yes\n";
			else
				cout << "no\n";
		}
	}
}
반응형

'Algorithm > 백준' 카테고리의 다른 글

[백준] 2164 카드2 with C++  (0) 2023.05.13
[백준] 1874 스택 수열 with C++  (0) 2023.05.12
[백준] 9012 괄호 with C++  (0) 2023.05.10
[백준] 10773 제로 with C++  (0) 2023.05.09
[백준] 10828 스택 with C++  (0) 2023.05.08