카테고리 없음

코딜리티 lesson7 Brackets, Fish(?), Nesting, StoneWall(?)

euuuuuz: 2022. 2. 25. 19:34

Brackets

[최초풀이]

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(S):
    if len(S) == 0:
        return 1
    if len(S) % 2 == 1:
        return 0
        
    stack = []

    for s in S:
        if s =='(' or s== '{' or s=='[':
            stack.append(s)
        elif s == ')':
            if len(stack) == 0:
                return 0
            if stack.pop() != '(':
                return 0
        elif s == '}':
            if len(stack) == 0:
                return 0
            if stack.pop() != '{':
                return 0
        elif s == ']':
            if len(stack) == 0:
                return 0
            if stack.pop() != '[':
                return 0
    if len(stack) != 0:
        return 0
    
    return 1

Fish

[최초풀이]

def solution(A, B):
    N = len(B)
    alive = []

    # 물고기 인덱스
    alive.append(0)

    i = 1
    while(i < N):
        if len(alive)==0:
            alive.appen(i)
        if B[i] == 0 and B[alive[-1]] == 1:
            if A[i] > A[alive[-1]] :
                alive.pop()
            else:
                i += 1 

        else:
            alive.append(i)
            i += 1

    return len(alive)

-> 무엇이 문제인지 아직도 모르겠다.

 

 

Nesting

[최초풀이]

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(S):
    while '()' in S:
        S = S.replace('()',"")

    if len(S) > 0:
        return 0
    return 1

[다른풀이]

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(S):
    stack = []
    for s in S:
        if s == '(':
            stack.append(s)
        else:
            if len(stack) == 0:
                return 0
            p = stack.pop() 
            if p != '(':
                stack.append(p)
                stack.append(s)
    if len(stack) == 0:
        return 1
    return 0

 

StoneWall