정신과 시간의 방
작성일
2024. 7. 10. 17:20
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main() 
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	while (true)
	{
		string str = "";
		getline(cin, str);

		if (str == ".")
		{
			break;
		}

		int flag = 0;
		stack<char> s;

		int strLength = str.length();

		for (int i = 0; i < strLength; i++)
		{
			if ((str[i] == '(') || (str[i] == '['))
			{
				s.push(str[i]);
			}
			else if (str[i] == ')') 
			{
				if (!s.empty() && s.top() == '(') 
				{
					s.pop();
				}
				else {
					flag = 1;
					break;
				}
			}
			else if (str[i] == ']') 
			{
				if (!s.empty() && s.top() == '[') 
				{
					s.pop();
				}
				else 
				{
					flag = 1;
					break;
				}
			}
		}

		if (flag == 0 && s.empty()) 
		{
			cout << "yes" << endl;
		}
		else {
			cout << "no" << endl;
		}
	}

	return 0;
}

 

  • 다시 풀이 (24-11-10)
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(0);

    while (true)
    {
        int flag = 0;
        stack<char> s;

        string input = "";
        getline(cin, input);  // 전체 입력을 받기

        if (input == ".")  // 입력이 온점(.)만 있을 경우 종료
        {
            break;
        }

        // 입력 문자열에서 괄호에 대한 처리를 시작
        for (char c : input)
        {
            if (c == ')')
            {
                if (s.empty() || s.top() != '(') // 짝이 맞는 열린괄호가 없다면 flag = 1
                {
                    flag = 1;
                    break;
                }
                else
                {
                    s.pop();
                }
            }
            else if (c == ']')
            {
                if (s.empty() || s.top() != '[')
                {
                    flag = 1;
                    break;
                }
                else
                {
                    s.pop();
                }
            }
            else if (c == '(' || c == '[')  // 열린 괄호일 경우에만 push
            {
                s.push(c);
            }
        }

        // 스택이 비어있지 않으면 짝이 맞지 않으므로 flag = 1
        if (!s.empty())
        {
            flag = 1;
        }

        if (flag == 1)
        {
            cout << "no" << '\n';
        }
        else
        {
            cout << "yes" << '\n';
        }
    }

    return 0;
}

 

  • 메모
    지난번에 풀었던 괄호 문제와 동일한 문제인데 괄호의 종류가 2가지라는 차이가 있다.
    stack을 사용해서 여는 괄호일 때만 push를 해서 체크하고, 닫는 괄호일 때 안을 조사해서 안에 push된 것이 없거나 push는 되어 있으나 해당하는 괄호의 여는 괄호가 아닌 경우에는 flag를 1로 체크해서 틀린 경우를 판별한다.

    https://risehyun.tistory.com/422
 

[백준/9012번/C++] 괄호

문제 풀이#include #include #includeusing namespace std;int main() { int cnt = 0; int flag = 0; // 중간에 스택이 비어있는 경우를 체크하기 위한 변수 string str; cin >> cnt; for (int i = 0; i buffer; cin >> str; int strLength = str.l

risehyun.tistory.com