프로그래밍/기타
[Python3][2020카카오공채] 괄호 변환
snoopybox
2019. 10. 4. 07:47
문제 :
https://www.welcomekakao.com/learn/courses/30/lessons/60058
나의 풀이 :
def solution(p):
trans = {'(': 1, ')': -1, 1: '(', -1: ')'}
def split(s):
e = trans[s[0]]
i = 1
while e != 0 and i < len(s):
e += trans[s[i]]
i += 1
return (s[:i], s[i:])
def is_correct(s):
e = 0
for c in s:
e += trans[c]
if e < 0:
return False
return True
def make_correct(u, v):
ret = '(%s)' % recursion(v)
for c in u[1:-1]:
ret += trans[-trans[c]]
return ret
def recursion(s):
if not s:
return s
u, v = split(s)
if is_correct(u):
return u + recursion(v)
return make_correct(u, v)
return recursion(p)