본문 바로가기

BOJ/Python

[BOJ/백준] 17413 - 단어 뒤집기 2 (Python)

문제

문제링크

<>안의 문자는 그대로, 나머지는 단어만 뒤집어서 출력하라.

 

풀이

문자열을 <> 내부 문자열은 유지하면서 split한다.

<과 >이 포함된 부분은 stack에 그대로 저장하고, 이외에는 공백 기준으로 단어 리스트를 생성한다.

각 단어를 뒤집고 뒤집힌 단어들을 공백과 다시 합쳐 stack에 추가한다.

stack 내 모든 요소를 문자열로 합쳐 리턴한다.

 

코드

import sys
input=sys.stdin.readline
import re

def reverse_w(s):
    tokens=re.split(r'(<[^<>]*>)',s)
    stack=[]

    for i in tokens:
        if i.startswith('<') and i.endswith('>'):
            stack.append(i)
        else:
            words=i.split(' ')
            stack.append(' '.join(w[::-1] for w in words))
    return ''.join(stack)

s=input().strip()
print(reverse_w(s))