백준/Stack, Queue

1406번 에디터

Snowboarder 2023. 1. 5. 14:48

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

 

1406번: 에디터

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수

www.acmicpc.net

문제풀이

  • 경우 4가지에 따라서 insert를 해준다고 생각을 하였다. 그러나 시간 복잡도가 너무 나왔다.
  • 경우에 따라 스택으로 (자료구조)로 계산하니 통과하였다.
  • 디테일 : 입력을 받을때 여러줄로 받을 필요 없이 range에서도 받을 수 있다.

코드

내풀이

import sys

word = sys.stdin.readline().strip()
word = list(word)
n = int(sys.stdin.readline())
key=[]
index = len(word)
max_index = len(word)



for i in range(n):
    key=[]
    key.append(list(sys.stdin.readline().split()))
    if key[0][0] == 'P':
        word.insert(index, key[0][1])
        if index < max_index:
            continue
        else :
            index +=1
            max_index = len(word)

    elif key[0][0] == 'L':
        if index == 0 :
            continue
        else:
            index -=1

    elif key[0][0] == 'D':
        if index >= max_index:
            continue
        else:
            index +=1
            
    elif key[0][0] == 'B':
        if index == 0:
            continue
        else :
            del(word[index-1])
            max_index = len(word)
            if index >= max_index:
                index -=1
            else:
                continue



print("".join(word))
string_list = list(input())
cursor = len(string_list)

for _ in range(int(input())):
    command = list(input().split())
    if command[0] == 'P':
        string_list.insert(cursor, command[1])
        cursor += 1
  
    elif command[0] == 'L':
        if cursor > 0:
            cursor -= 1

    elif command[0] =='D':
        if cursor < len(string_list):
            cursor += 1
  
    else:
        if cursor > 0:
            string_list.remove(string_list[cursor-1])

print(''.join(string_list))

다른사람풀이

import sys

st1 = list(sys.stdin.readline().rstrip())
st2 = []

for _ in range(int(sys.stdin.readline())):
	command = list(sys.stdin.readline().split())
    if command[0] == 'L':
		if st1:
        	st2.append(st1.pop())
            
	elif command[0] == 'D':
    	if st2:
        	st1.append(st2.pop())

	elif command[0] == 'B':
    	if st1:
        	st1.pop()
            
	else:
    	st1.append(command[1])
        
st1.extend(reversed(st2))
print(''.join(st1))
import sys

stack_l = list(input())
stack_r = []
n = int(input())

for i in range(n):
    command = sys.stdin.readline().split()

    if command[0] == "L" and stack_l:
        stack_r.append(stack_l.pop())
    elif command[0] == "D" and stack_r:
        stack_l.append(stack_r.pop())
    elif command[0] == "B" and stack_l:
        stack_l.pop()
    elif command[0] == "P":
        stack_l.append(command[1])

print("".join(stack_l + list(reversed(stack_r))))

위 코드의 접근법은, 커서를 기준으로 문자열을 스택 두개에 나누어 담겠다는 것이다.

 

 

이렇게하면, 값을 추가하거나 삭제하는 연산, 커서를 이동하는 연산 모두 append와 pop을 통해 할 수 있어 O(1) 시간의 연산을 보장한다.

 

반복문에서 명령을 모두 수행한 후, stack2를 뒤집어준 후 extend 함수를 활용해 두 stack을 합쳐주었다.

 

'백준 > Stack, Queue' 카테고리의 다른 글

9093번 단어 뒤집기  (0) 2023.01.04
1874번 스택 수열  (0) 2022.09.17