プログラマ12909:右かっこ

1750 ワード

[質問欄#(プログラマ12909:右かっこ)
#include<string>
#include <iostream>
#include<stack>

using namespace std;

bool solution(string s)
{
    bool answer = true;
    stack<char> st;
    int i = 0;
    
    while (true)
    {
        char c = s[i];
        if (c=='(' ) 
        {
            st.push(c);
        }
        else if (c == ')' ) {
            if (st.size() > 0) {
                if ( st.top() == '(' && c == ')') {
                    st.pop();
                }
                else {
                    answer = false;
                    break;
                }
               }
            else {
                answer = false;
                break;
            }
            }
        else //맨 마지막까지 stack이 비어지지 않는 경우는 false(괄호 짝이 안맞는 경우임)
        {
            if (st.empty()) {
                answer = true;
                break;
            }
            else {
                answer = false;
                break;
            }
        }
        i++;
    }
   
    return answer;
}