본문 바로가기
개발/알고리즘

[codility] Nesting

by ny0011 2021. 2. 20.
반응형

app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/

 

Nesting coding task - Learn to Code - Codility

Determine whether a given string of parentheses (single type) is properly nested.

app.codility.com

12프로

ㅋㅋㅋㅋㅋㅋㅋㅋㅋ

)( 생각을 못했다ㅎㅎㅎ

def solution(S):
    # write your code in Python 3.6
    if len(S) == 0:
        return 1
    if len(S) % 2 == 1:
        return 0

    left = S.count("(")
    right = S.count(")")
    if left == right : 
        return 1
    else:
        return 0

 

"("만 담는 stack을 둬서 ")"가 오면 pop을 하고

stack 길이가 0인데 ")"가 오면 0을 리턴

def solution(S):
    # write your code in Python 3.6
    if len(S) == 0:
        return 1
    if len(S) % 2 == 1:
        return 0

    stack = []
    for i in S:
        if i == "(":
            stack.append(i)
        else:
            if len(stack) == 0:
                return 0
            else:
                stack.pop()
    if len(stack) == 0:
        return 1
    else:
        return 0

'개발 > 알고리즘' 카테고리의 다른 글

[codility] Fish  (0) 2021.02.20
[codility] Brackets  (0) 2021.02.19
[codility] Triangle  (0) 2021.02.19
[codility] NumberOfDiscIntersections  (0) 2021.02.19
[codility] MaxProductOfThree  (0) 2021.02.19

댓글