동캄의 코딩도장

백준 1541 [잃어버린 괄호] 파이썬 본문

코테/BOJ

백준 1541 [잃어버린 괄호] 파이썬

동 캄 2022. 9. 4. 23:49

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

 

1541번: 잃어버린 괄호

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

www.acmicpc.net

#백준 1541
import sys
s=sys.stdin.readline().rstrip()
lst=list(map(str,s.split('-')))
for i in range(len(lst)):
    if '+' in lst[i]:
        k=list(map(int,lst[i].split('+')))
        lst[i]=sum(k)
    else:
        lst[i]=int(lst[i])
ans=lst[0]
for i in range(1,len(lst)):
    ans-=lst[i]

print(ans)
#다른풀이
a = input().split('-')
num = []
for i in a:
    cnt = 0
    s = i.split('+')
    for j in s:
        cnt += int(j)
    num.append(cnt)
n = num[0]
for i in range(1, len(num)):
    n -= num[i]
print(n)

그리디하게 해결하면 된다.