#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
bool checkStr(string s){
stack<char> check;
check.push(s[0]);
for(int i=1;i<s.length();i++){
if(!check.empty() && (check.top() == '(' && s[i] == ')')) check.pop();
else check.push(s[i]);
}
if(check.empty()) return true;
return false;
}
string recur(string w){
string u="",v="";
stack<char> div;
if(w.length() == 0) return "";
if(checkStr(w)) return w;
div.push(w[0]);
for(int i=1;i<w.length();i++){
if((div.top()=='(' && w[i]==')') || (div.top()==')' && w[i]=='(')){
div.pop();
if(div.empty()){
u = w.substr(0,i+1);
v = w.substr(i+1);
break;
}
}else div.push(w[i]);
}
bool result = checkStr(u);
string str;
if(result == true) str = u + recur(v);
else{
string newU="";
u.erase(0,1);
u.erase(u.length()-1,1);
for(int i=0;i<u.length();i++) newU += (u[i] == '(' ? ")" : "(");
str = "("+ recur(v) +")" + newU;
}
return str;
}
string solution(string p) {
string answer = "";
answer = recur(p);
return answer;
}
- 정해진 로직에 따라 차근차근 구현하면 풀리는 문제