[21322][伯俊/BOJ]4949号均衡の世界


質問する



にゅうしゅつりょく



に答える


STL stackで問題を解決しました.
  • 「出れば押す」
  • 「[」が出れば押す
  • 「」の場合スタックが空白ではなくtopが「(」の場合pop、そうでない場合push.
  • 「」の場合スタックが空白ではなく、topが「[」の場合pop、そうでない場合push.
  • 3、4回else、例えば()[]と一緒に「」、「]」を出しても押されず、スタックが空いていると判断した場合は例外処理を行わなければならない.
  • コード#コード#

    #include <bits/stdc++.h>
    using namespace std;
    
    int main()
    {
    	while (true)
    	{
    		stack<char>s;
    		string str;
    		getline(cin, str);
    
    		if (str[0] == '.')
    			break;
    		for (int i = 0; str[i] != '\0'; ++i)
    		{
    			if (str[i] == '(')
    				s.push(str[i]);
    			if (str[i] == '[')
    				s.push(str[i]);
    			if (str[i] == ')')
    			{
    				if (!s.empty() && s.top() == '(')
    					s.pop();
    				else
    					s.push(str[i]);
    			}
    			if (str[i] == ']')
    			{
    				if (!s.empty() && s.top() == '[')
    					s.pop();
    				else
    					s.push(str[i]);
    			}
    		}
    		if (s.empty())
    			cout << "yes" << '\n';
    		else
    			cout << "no" << '\n';
    	}
    }