2020 KAKAO BLIND RECRUITMENT - 괄호 변환 (Level 2)

 

https://programmers.co.kr/learn/courses/30/lessons/60058


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def get_balance(w):
    n_open = 0
    n_close = 0
    for i, c in enumerate(w):
        n_open = n_open + 1 if c == '(' else n_open
        n_close = n_close + 1 if c == ')' else n_close
        if n_open == n_close:
            return [w[:i + 1], w[i + 1:]]
    return "", ""


def check_correct(w):
    while True:
        if w == '':
            return True
        elif '()' in w:
            w = w.replace('()', '')
        else:
            return False


def get_correct(w):
    if w == '':
        return w
    u, v = get_balance(w)
    #     print("u:", u, "v:", v)
    #     print("chk(u):", check_correct(u))
    if check_correct(u):
        return f"{u}{get_correct(v)}"
    else:
        rst = f"({get_correct(v)})"
        u = u[1:-1].replace('(', 't').replace(')', '(').replace('t', ')')
        return f"{rst}{u}"


def solution(w):
    return get_correct(w)

Complexity

$O(n^2)$
$n = |w|$