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

 

17413번: 단어 뒤집기 2

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

www.acmicpc.net

 

풀이 과정

단어를 뒤집으려면 스택에 넣었다 빼면 된다. 문자를 한글자씩 읽으면서 stack에 넣다가 tag의 시작인 '<'이나 공백 문자를 인식하면 스택에 있는 모든 문자를 스택 탑부터 출력하고, 인식한 단어를 출력하면 된다. '<'을 인식했으면 '>'을 인식하기 전까지의 단어는 스택에 넣는 과정 없이 그냥 출력해주면 된다.

 

코드

import sys

strInput = list(sys.stdin.readline().rstrip())
strInput.append(' ')
strInput2 = []
tagFlag = False
for i in strInput:
    if i == '<':
        while strInput2:
            print(strInput2.pop(), end='')
        tagFlag = True
        print('<', end='')
    elif i == '>':
        tagFlag = False
        print('>', end='')
    elif i == ' ':
        if tagFlag: print(' ', end='')
        else:
            while strInput2:
                print(strInput2.pop(), end='')
            print(' ', end='')
    else:
        if tagFlag: print(i, end='')
        else: strInput2.append(i)

+ Recent posts