study/백준(BOJ)

[Python] 1541. 잃어버린 괄호

bbooo 2023. 5. 12. 01:10
728x90

https://www.acmicpc.net/problem/1541

 

1541번: 잃어버린 괄호

첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다

www.acmicpc.net

 

접근법

  • -를 기준으로 input을 분리해서 모두 더하면 된다.
def input_func():
    arr = input().split("-")
    return arr

def solution(arr):
    ans = 0
    for idx, num in enumerate(arr):
        # 처음 시작 숫자가 음수인경우 고려
        if idx == 0:
            temp = sum(map(int, num.split("+")))
            if num[0] == "-":
                ans -= int(temp)
                continue
            ans += int(temp)
            continue

        temp = sum(map(int, num.split("+")))
        ans -= temp
    print(ans)

def main():
    arr = input_func()
    solution(arr)

if __name__ == '__main__':
    main()


사용된 알고리즘

수학, 문자열, 그리디 알고리즘, 파싱

728x90