[Programmers] 괄호 변환

Time Lapse :NONE

solution.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <string>
#include <vector>

using namespace std;
bool isPair(string u)
{
int stat = 0;
for(int i=0;i<u.length();i++)
{
if(u.at(i)=='(')
stat++;
else
stat--;
if(stat<0)
return false;
}
return true;
}
string solution(string p) {
string answer = "";
if(p.length()==0)
return answer;
string u;
string v;
int stat=0;
for(int i=0;i<p.length();i++)
{
if(p.at(i)=='(')
stat++;
else
stat--;
if(stat==0)
{
stat=i;
break;
}
}
u=p.substr(0,stat+1);
v=p.substr(stat+1,p.length()-stat-1);
if(isPair(u))
{
answer+=u;
answer+=solution(v);
}
else
{
answer+='(';
answer+=solution(v);
answer+=')';
u.erase(u.end()-1);
u.erase(u.begin());
for(int i=0;i<u.length();i++)
{
if(u.at(i)=='(')
answer+=')';
else
answer+='(';
}
}

return answer;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/Programmers/exchangeBarket/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.