본문 바로가기
알고리즘/[python] 백준 BOJ

[Python] 백준 17413 단어 뒤집기2

by Alan_Kim 2022. 12. 14.
728x90
반응형

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

 

17413번: 단어 뒤집기 2

문자열 S가 주어졌을 때, 이 문자열에서 단어만 뒤집으려고 한다. 먼저, 문자열 S는 아래와과 같은 규칙을 지킨다. 알파벳 소문자('a'-'z'), 숫자('0'-'9'), 공백(' '), 특수 문자('<', '>')로만 이루어져

www.acmicpc.net

문제 전략

- '<word>' 와 word 는 출력 값이 다른데 어떻게 구현할 것인가?

- 띄어쓰기 마다 단어를 뒤집을 것인데 어떻게 표현할 것인가? => isalnum 을 사용해 alphabet이나 number가 아닌 것과 구별 아니면 띄어쓰기로 인식하고 reverse()를 이용하여 단어 뒤집기!

 

import sys
input = sys.stdin.readline

if __name__=='__main__':
    sentence = list(input().strip())
    i = 0
    start = 0
    while i < len(sentence):
        if sentence[i] == '<':
            i+=1
            while sentence[i] != '>':
                i+=1
            i += 1 # 괄호가 닫혔을 때 인덱스 하나 증가
        elif sentence[i].isalnum(): #숫자나 알파벳을 만나면
            start = i
            while i< len(sentence) and sentence[i].isalnum():
                i +=1
            word = sentence[start:i]
            word.reverse()
            sentence[start:i] = word
        else:
            i += 1
	print(''.join(sentence))
728x90
반응형

댓글