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

문제

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

코드

import sys

input = list(sys.stdin.readline().rstrip())
result = []
temp = []
i = 0

while i < len(input):
    if input[i] == '<':
        if len(temp) != 0:
            count = len(temp)
            for j in range(count):
                result.append(temp.pop())
        result.append(input[i])
        i += 1

        while input[i] != '>':
            result.append(input[i])
            i += 1
        result.append(input[i])
        i += 1

    elif input[i] == ' ':
        if len(temp) != 0:
            count = len(temp)
            for j in range(count):
                result.append(temp.pop())
        result.append(input[i])
        i += 1

    else:
        temp.append(input[i])
        i += 1

if len(temp) != 0:
    count = len(temp)
    for j in range(count):
        result.append(temp.pop())

print(''.join(result))
            

결과


정리

개념

입력받은 input을 리스트화(?)하면 \n(엔터)까지 포함되어 저장되기 때문에 input을 입력받을때 rstrip()라는 것을 사용했다.

rstrip('str'): 문자열의 오른쪽에서 str를 제거

1) str을 입력하지 않았을때 (=인자를 입력하지 않았을때): 문자열 오른쪽에 공백이 있다면 공백을 제거

#1 인자가 없을때
print('Hello '.rstrip())       #Hello

2) str이 한글자일때: 문자열의 오른쪽에서 그 문자와 동일한 문자를 모두 제거

#2 인자가 한글자일때
print('apple'.rstrip('e'))     #appl

3) str이 여러글자일때: 문자열 오른쪽에 str의 모든 조합을 제거

#3 인자가 여러글자일때
print('apple'.rstrip('lep'))   #a

코드(주석o)

import sys

input = list(sys.stdin.readline().rstrip())
# 문자열을 한글자씩 끊어서 리스트로 저장하기
# rstrip(): \n를 제외하고 저장하기 위해 사용

result = []
temp = []
i = 0

while i < len(input):
    
    # '<' 를 만났을때
    if input[i] == '<':
        if len(temp) != 0: # temp의 길이가 0이 아닐때 = 뒤집어야 되는 단어가 있을때
            count = len(temp)
            for j in range(count): # temp의 길이만큼 반복
                result.append(temp.pop()) # temp 리스트에서 pop해서 result 리스트에 append해줌
        result.append(input[i]) # '<'를 append해줌 
        i += 1

        # '>'를 만날때까지 반복
        while input[i] != '>': 
            result.append(input[i]) # 괄호안에 있는 문자들은 뒤집지 않기 때문에 바로 result 리스트에 append해줌
            i += 1
        result.append(input[i]) # '>'를 append해줌
        i += 1

    # 띄어쓰기를 만났을때
    elif input[i] == ' ': 
        if len(temp) != 0: # 위 코드와 동일
            count = len(temp) 
            for j in range(count): 
                result.append(temp.pop()) 
        result.append(input[i]) # 띄어쓰기를 append해줌
        i += 1

    # 그냥 평범한 글자일때 (=숫자, 문자일때)
    else:
        temp.append(input[i]) # 뒤집어야되는 글자들이기 때문에 result가 아닌 temp에 넣어줌
        i += 1

# 입력받은 문자열로 while문을 돌고 나왔을때
# temp 길이가 0이 아니라는 것은 뒤집어야 되는 단어가 있다는 뜻
if len(temp) != 0: # 위 코드와 동일
    count = len(temp) 
    for j in range(count): 
        result.append(temp.pop()) 

print(''.join(result))

느낀점

처음에는 for문으로 구현하려고 했는데 변수랑 if문이 많아져서 복잡해지는 것 같아서 while문으로 바꿨다. 근데 while문도 복잡해..ㅎㅋㅋㅋㅋ 그냥 for문으로 구현했어도 복잡한건 비슷했을 것 같다😂 어찌저찌 구현은 했는데 코드가 뭔가 비효율적인 것 같다,,,ㅠㅠ 나중에 이 문제를 까먹을때쯤 한번 더 풀어보고 싶다..!

좋은 웹페이지 즐겨찾기