baekjoon

백준 17413

finite라이프 2023. 8. 7. 16:04

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

 

17413번: 단어 뒤집기 2

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

www.acmicpc.net

ins = input()
firstGi = 0 # <가 나오는 인덱스 넘버 저장
lastGi = 0 # >가 나오는 인덱스 넘버 저장
storage = [] # <> 또는 띄어쓰기를 기준으로 split하여 storage에 저장
flag = False # <>안의 글자는 flag가 true일떄.
tem = ''
save_space=[] # 입력한 문자열에서 띄어쓰기공간의 인덱스 넘버를 저장하기 위한 배열
for i in range(len(ins)):
    if not flag and ins[i] == ' ':
        save_space.append(i)
    if not flag and (ins[i] != '<' and ins[i] != ' '): # false일때
        tem += ins[i]
    if not flag and (ins[i] == ' ' or i == len(ins)-1 or ins[i+1]=='<'):
        if tem: # tem이 빈 문자열이 아닌 채워져있는 문자열이라면
            storage.append(tem[::-1]) #거꾸로 저장한다.
        tem = ''
    if ins[i]=='<':
        firstGi = i
        flag = True
    elif ins[i]=='>':
        lastGi = i
        storage.append(ins[firstGi:lastGi+1])
        flag = False
total = ''

index = 0  # save_space 리스트의 인덱스를 추적

for i in storage:
    total += i
    try:
        if len(total) == save_space[index]:
            total += " "
            index += 1  # 다음 공백 위치로 이동
            #print(total + "*")
    except Exception as e:
        pass  # 빈 예외 처리 블록으로 변경

print(total)
ins = input()
storage = []
n = len(ins)
i = 0

while ins:
    a = False
    if ins[0] == '<':
        for j in range(1,len(ins)):
            if ins[j] == '>':
                storage.append(ins[0:j+1])
                ins = ins[j+1:]
                break

    elif ins[0] != '<':
        for j in range(1,len(ins)):
            if ins[j] == '<':
                storage.append(ins[0:j])
                ins = ins[j:]
                a = True
                break
            if ins[j-1] == ' ':
                storage.append(ins[0:j-1])
                storage.append(' ')
                ins = ins[j:]
                a = True
                break
        if a:
            continue

        for j in range(0,len(ins)):
            if j== len(ins)-1:
                storage.append(ins)
                i = 1

    if i == 1:
        break

for i in storage:
    if i.startswith('<'):
        print(i,end='')
    else:
        print(i[::-1],end='')

두번째로 푼게 메모리는 같지만 속도는 5배정도 빨랐다.

아래는 다른사람의 풀이

s = input() + " "
stack, answer = [], []
tag = False
print(stack,answer)
for i in s:
    if i == "<":
        while stack:
            #print(stack,end=' ')
            answer.append(stack.pop())
        tag = True
    if i == ">":
        tag = False
        answer.append(i)
        continue

    if tag:
        answer.append(i)
    else:
        if i == " ":
            while stack:
                answer.append(stack.pop())
            answer.append(i)
        else:
            stack.append(i)

print(*answer, sep="")

https://www.acmicpc.net/source/64687609

 

로그인

 

www.acmicpc.net