2020 KAKAO BLIND RECRUITMENT
- Lv 2. 괄호 변환 (Python)
https://school.programmers.co.kr/learn/courses/30/lessons/60058
def check_perfect(string):
left_bracket = []
check = True
for i in range(len(string)):
if (string[i] == '('):
left_bracket.append(string[i])
elif (string[i] == ')'):
if (left_bracket):
left_bracket.pop()
else:
check = False
return check
def split_u_v(string):
left_cnt, right_cnt = 0, 0
u, v = '', ''
if (len(string) == 0):
return u, v
for i in range(len(string)):
if (string[i] == '('):
left_cnt += 1
elif (string[i] == ')'):
right_cnt += 1
if (left_cnt == right_cnt):
u = string[:i + 1]
v = string[i + 1:]
break
return u, v
def reverse_bracket(string):
reverse_str = ''
for i in range(len(string)):
if (string[i] == '('):
reverse_str += ')'
if (string[i] == ')'):
reverse_str += '('
return reverse_str
def solution(p):
# p가 올바른 괄호 문자열인지 확인
if (check_perfect(p)):
return p
u, v = split_u_v(p)
if(check_perfect(u)):
return u + solution(v)
else:
answer = '(' + solution(v) + ')' + reverse_bracket(u[1:-1])
return answer
solution(v)
로 수행하면 되는 것이었다.!!!def check_perfect(string):
left_bracket = []
check = True
for i in range(len(string)):
if (string[i] == '('):
left_bracket.append(string[i])
elif (string[i] == ')'):
if (left_bracket):
left_bracket.pop()
else:
check = False
return check
def split_u_v(string):
left_cnt, right_cnt = 0, 0
u, v = '', ''
if (len(string) == 0):
return u, v
for i in range(len(string)):
if (string[i] == '('):
left_cnt += 1
elif (string[i] == ')'):
right_cnt += 1
if (left_cnt == right_cnt):
u = string[:i + 1]
v = string[i + 1:]
break
return u, v
def reverse_bracket(string):
reverse_str = ''
for i in range(len(string)):
if (string[i] == '('):
reverse_str += ')'
if (string[i] == ')'):
reverse_str += '('
return reverse_str
def solution(p):
answer = ''
u, v = '', ''
new_u, new_v = '', ''
sub = ''
# p가 올바른 괄호 문자열인지 확인
check = check_perfect(p)
if (check):
return p
# p가 올바른 괄호 문자열이 아니라면
list_u = []
list_v = []
if (check == False):
u, v = split_u_v(p)
list_u.append(u)
list_v.append(v)
new_u = u
while (check_perfect(new_u) == True):
new_u, new_v = split_u_v(v)
list_u.append(new_u)
list_v.append(new_v)
v = new_v
sub_list_u = []
for i in range(len(list_v) - 1, -1, -1):
if (check_perfect(list_u[i]) == False):
sub += '(' + list_v[i] + ')' + reverse_bracket(list_u[i][1:-1])
elif (check_perfect(list_u[i]) == True):
sub_list_u.append(list_u[i])
for j in range(len(sub_list_u)):
sub = sub_list_u[j] + sub
sub_list_u.pop()
answer = sub
return answer
if __name__ == '__main__':
print(solution("()))((()")) # "()(())()"