본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 괄호 변환

728x90

 

 

나의 풀이

def check(p):
    stack = []
    for x in p:
        if x == '(':
            stack.append(x)
        else:
            if stack and stack[-1] == '(':
                stack.pop()
            else:
                return False
    return True



def solution(p):
    if check(p):
        return p

    u, v = p, ''

    for i in range(1, len(p)):
        if p[:i].count('(') == p[:i].count(')'):
            u, v = p[:i], p[i:]
            break

    if check(u):
        return u + solution(v)

    return '(' + solution(v) + ')' + ''.join(list(map(lambda x: '(' if x == ')' else ')', list(u[1:-1]))))

 

 

 

다른 풀이

def solution(p):
    if p=='': return p
    r=True; c=0
    for i in range(len(p)):
        if p[i]=='(': c-=1
        else: c+=1
        if c>0: r=False
        if c==0:
            if r:
                return p[:i+1]+solution(p[i+1:])
            else:
                return '('+solution(p[i+1:])+')'+''.join(list(map(lambda x:'(' if x==')' else ')',p[1:i]) ))

 

 

반응형