Algorithm & DataStructure
[Backjoon] 단어 뒤집기 2
GeonWoo Kim
2020. 11. 26. 12:04
문자열을 뒤집는 문제는 프로그래머의 기본이 되어있는지 판단할 수 있는 문제라고 한다. 17413번 단어 뒤집기 2는 단순히 배열을 뒤집는 것에서 넘어 특정 조건에 맞는 문자열만 뒤집는 문제이다.
투 포인터와 큐를 이용해서 풀면 되겠다고 생각했고, 깔끔하지 못한 코딩이였지만 한번에 정답을 맞출 수 있었다. 다른 사람들의 풀이를 보면 문자열을 문자단위로 분해해서 순회하는 방법, 스택을 이용하는 방법들도 있었다. 아래는 소스코드이다.
import sys
from collections import deque
if __name__ == "__main__":
q = deque()
target_string = sys.stdin.readline().replace("\n", "")
idx_start, idx_end = 0, 0
is_tag_open = False
while idx_start < len(target_string):
if target_string[idx_start] == "<":
while idx_end < len(target_string) and target_string[idx_end] != ">" :
idx_end += 1
idx_end += 1
q.append(target_string[idx_start:idx_end])
idx_start = idx_end
else:
while idx_end < len(target_string) and target_string[idx_end] != "<":
idx_end += 1
q.append(target_string[idx_start:idx_end])
idx_start = idx_end
answer_string = ""
while q:
string = q.popleft()
if "<" in string:
answer_string += string
else:
temp_arr = string.split(" ")
temp_arr = [temp[::-1] for temp in temp_arr]
answer_string += " ".join(temp_arr)
print(answer_string)