STUDY/Algorithm

[프로그래머스] 2020카카오공채 괄호 변환, python3

sinawi95 2020. 1. 2. 12:00
728x90

def solution(p):
    answer = chk(p)
    return answer

def chk(p):
    if p=="":
        return ""
    else:
        u,v=devide(p)
        if chk_right(u):
            return u+chk(v)
        else:
            u_inverse=""
            for i in u:
                if i =="(":
                    u_inverse+=")"
                elif i ==")":
                    u_inverse+="("
            return "("+chk(v)+")"+u_inverse[1:-1]

def chk_right(p):# check p is right
    l_num=0
    r_num=0
    for ch in p:
        if ch=='(':
            l_num+=1
        elif ch==')':
            r_num+=1
        if r_num>l_num:
            right=0
            break
        else:
            right=1
    return right

def devide(p):
    l_num=0
    r_num=0
    for ch in p:
        if ch=='(':
            l_num+=1
        elif ch==')':
            r_num+=1
        if l_num==r_num:
            break
    u=p[:2*l_num]
    v=p[2*l_num:]
    return (u,v)