Algorithm (Python & Java)/구현

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

DH_0518 2023. 1. 8. 22:29

알고리즘 분류 : 구현, 자료 구조, 문자열, 스택

시간 복잡도 : ...

 

Try_1) Success

'''
Condition
    - TL : 1s (약 2000만번 연산)
    - ML : 512mb (약 128 * 100만개의 데이터)
    - 1<=S<=10만
    - S의 시작,끝은 공백이 아니다
    - '<'와 '>'는 순서대로, 항상 쌍을 이루어서 등장한다
    - 태그를 제외하고 모두 뒤집는다

Question
    - S를 뒤집어서 출력하여라

Access
    - 태그와 태그사이의 단어를 저장하는 temp를 활용한다
'''
from typing import List
from sys import stdin
input = stdin.readline

#define function
def solution(string:List) -> List:
    result=[]
    temp = []
    idx = 0
    # 뒤집기 시작
    while idx < len(string):
        s = string[idx]
        #태그인 경우
        if s == '<':
            result += reversed(temp) # '<'이전 단어들 뒤집음
            result.append('<')
            temp=[] # temp초기화

            idx +=1
            s = string[idx]
            while s != '>': # '>'만나기 전까지 그대로 대입
                result.append(s)
                idx +=1
                s = string[idx]
            result.append('>') #'>' 만나면 '>' 대입하고 태그 끝냄
        #공백인 경우
        elif s == ' ':
            result += reversed(temp)
            result.append(' ')
            temp=[]
        else:
            temp.append(s)
        idx +=1
    if temp:
        result += reversed(temp)
    return ''.join(result) # type: ignore

#input&set data
string=list(input().strip())

#main()
print(solution(string))