[알고리즘/백준] 17413: 단어 뒤집기2(python)

유현민·2022년 4월 5일
0

알고리즘

목록 보기
96/253

다른 방법 말고 큐랑 스택을 이용해서 풀고 싶었다.

from collections import deque
from sys import stdin

S = list(stdin.readline().strip())
stack = []
q = deque()
res = ''
flag = True  # 괄호 안은 False 밖은 True
for i in S:
    if i == '<':
        while stack:
            res += stack.pop()
        q.append(i)
        flag = False
    elif i == '>':
        q.append(i)
        while q:
            res += q.popleft()
        flag = True

    elif i == ' ':
        if flag:
            while stack:
                res += stack.pop()
            res += ' '
        else:
            q.append(i)
            while q:
                res += q.popleft()

    else:
        if flag:
            stack.append(i)
        else:
            q.append(i)
while stack:
    res += stack.pop()
print(res)
profile
smilegate megaport infra

0개의 댓글