[프로그래머스] 괄호 변환 (python 파이썬)

코딩하는계란·2021년 5월 6일
0

프로그래머스

목록 보기
9/16
post-thumbnail

👉 괄호 변환



✍ 내 코드


# 2020 KAKAO BLIND RECRUITMENT  괄호 변환
def solution(p):
    def devide(st):
        open_cnt = 0
        close_cnt = 0
        u = v = ""
        idx = 0
        if st and st[idx] == "(":
            u += "("
            open_cnt += 1

        elif st and st[idx] == ")":
            u += ")"
            close_cnt += 1
        idx += 1

        while open_cnt != close_cnt:
            if idx < len(st) and st[idx] == "(":
                u += "("
                open_cnt += 1
            elif idx < len(st) and st[idx] == ")":
                u += ")"
                close_cnt += 1
            idx += 1

        if idx < len(st):
            v = st[idx:]

        return u, v

    def check(st):
        stack = []
        for i in st:
            if stack and i == ")" and stack[-1] == "(":
                stack.pop()
            else:
                stack.append(i)
        if not stack:
            return 1
        else:
            return 0

    def reverse(st):
        result = ""
        for i in st:
            result += "(" if i == ")" else ")"
        return result

    def recursive(st):
        result = ""
        if st == "":
            return st

        u, v = devide(st)
        if check(u):
            result += u
            result += recursive(v)

        else:
            result = "("
            result += recursive(v) + ")"
            u = u[1:-1]
            result += reverse(u)
        return result

    return recursive(p)


✍ 팁

  • 괄호 나누기, 올바른지 확인하기 등의 작업을 함수화 하여 생각하면 간단하다.
  • 더 짧은 코딩이 가능하나 가독성에서도 이정도는 과정이 잘보이도록 코딩하는게 더좋다 생각했다.
profile
코딩💻 고양이😺

0개의 댓글