본문 바로가기
Problem Solving/Codility

[Python] 7.1. Brackets

by 부르르 2021. 3. 27.

https://app.codility.com/demo/results/trainingU6MG2S-N29/

 

Test results - Codility

A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: S is empty; S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; S has the form "VW" where V and W are properly nes

app.codility.com


Task Score

100%

Correctness

100%

Performance

100%

Detected time complexity

O(N)

def solution(S):
    stack = []
    brackets = {"(":")", "{":"}", "[":"]"}
    for s in S:
        if s in brackets.keys():
            stack.append(s)
        elif s in brackets.values():
            if stack:
                c = stack.pop()
                if brackets[c] != s:
                    return 0
            else:
                return 0
    if stack:
        return 0
    return 1

 

문제를 푸는데 도움이 된 테스트 케이스

'['
']'
''
']['
'vvv'

 

728x90
반응형

'Problem Solving > Codility' 카테고리의 다른 글

[Python] 7.3. Nesting  (0) 2021.03.30
[Python] 7.2. Fish  (0) 2021.03.29
[Python] 6.4. Triangle  (0) 2021.03.26
[Python] 6.3. NumberOfDiscIntersections  (0) 2021.03.25
[Python] 6.2. MaxProductOfThree  (0) 2021.03.25

댓글