【Algorithm】 [프머] 코딩테스트연습/ 스택, 큐/ 쇠막대기

문제 사이트 [https://programmers.co.kr/learn/courses/30/lessons/42585]

손코딩

img

나의 코드

def solution(arr):
    start_stack = []
    answer = 0
    
    for i in range(len(arr)):
        if arr[i] == '(':
            start_stack.append(i)
        else:
            diff = i - start_stack.pop()
            if diff == 1:
                answer += len(start_stack)
            else:
                answer += 1
                
    return answer

좋은 코드

def solution(arrangement):
    answer = 0
    sticks = 0
    rasor_to_zero = arrangement.replace('()','0')

    for i in rasor_to_zero:
        if i == '(':
            sticks += 1
        elif i =='0' :
            answer += sticks
        else :
            sticks -= 1
            answer += 1

    return answer
    
***
    
def solution(arrangement):
    answer = 0
    stack = 0
    laseron = False
    for p in arrangement:
        if p == '(':
            laseron = True
            stack += 1
        else:
            if laseron==True:
                answer += stack-1
                laseron=False
            else:
                answer += 1
            stack -= 1

    return answer
    
    
***
    
    
def solution(arrangement):
    onLaser = 0
    total = 0

    for i in range(len(arrangement) - 1):
        if arrangement[i:i+2] == '((':
            onLaser += 1
        elif arrangement[i:i+2] == '))':
            onLaser -= 1
            total += 1
        elif arrangement[i:i+2] == '()':
            total += onLaser

    return total

© All rights reserved By Junha Song.