#include <string>
#include <vector>
#include <stack>
using namespace std;
 
int isRight(string p)
{
    stack<char> st;
    
    for(int i = 0; i < p.size(); i++)
    {
        if(p[i] == '(')
        {
            st.push(p[i]);
        }
        else
        {
            if(st.empty())
            {
                return 0;
            }
            
            st.pop();
        }
    }
    
    if(st.empty())
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
 
string solution(string p) 
{
    // 이미 올바른 문자열이면 출력
    if(isRight(p) == 1)
    {
        return p;
    }
    
    string answer = "";
    string u = "";
    string v = "";
    
    int leftCnt = 0;
    int rightCnt = 0;
    
    // 1
    if(p == "")
    {
        return "";
    }
    
    // 2
    for(int i = 0; i < p.size(); i++)
    {
        if(p[i] == '(')
        {
            leftCnt++;
        }
        else
        {
            rightCnt++;
        }
        
        if(leftCnt == rightCnt)
        {
            u = p.substr(0, leftCnt+rightCnt);
            v = p.substr(leftCnt+rightCnt, p.size()-(leftCnt+rightCnt));    
            break;
        }
    }
    
    // 3
    if(isRight(u) == 1)
    {
        answer += u;
        string temp = solution(v);
        answer += temp;
    }
    // 4
    else
    {
        // 4-1 ~ 4-3
        string temp1 = "(";
        string temp2 = solution(v);
        temp1 += temp2;
        temp1 += ")";
        
        // 4-4, remove 
        string temp3 = u.substr(1, u.size()-2);
        
        // 4-4, reverse
        temp2 = "";
        for(int i = 0; i < temp3.size(); i++)
        {
            if(temp3[i] == '(')
            {
                temp2 += ')';
            }
            else
            {
                temp2 += '(';
            }
        }
        
        temp1 += temp2;
        answer = temp1;
    }
    
    return answer;
}
cs

+ Recent posts