๐ŸŒฑ → ๐ŸŒณ

[๋ฐฑ์ค€] 1406๋ฒˆ: ์—๋””ํ„ฐ python ๋ณธ๋ฌธ

Algorithms

[๋ฐฑ์ค€] 1406๋ฒˆ: ์—๋””ํ„ฐ python

BAY 2023. 1. 5. 12:35
728x90

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

 

1406๋ฒˆ: ์—๋””ํ„ฐ

์ฒซ์งธ ์ค„์—๋Š” ์ดˆ๊ธฐ์— ํŽธ์ง‘๊ธฐ์— ์ž…๋ ฅ๋˜์–ด ์žˆ๋Š” ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ์ด ๋ฌธ์ž์—ด์€ ๊ธธ์ด๊ฐ€ N์ด๊ณ , ์˜์–ด ์†Œ๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ๊ธธ์ด๋Š” 100,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ์ž…๋ ฅํ•  ๋ช…๋ น์–ด์˜ ๊ฐœ์ˆ˜

www.acmicpc.net

 

 

๋ˆˆ๋ฌผ ์ค„์ค„ .. 

์‚ฝ์งˆ์— ์‚ฝ์งˆ์— ์‚ฝ์งˆ์— ์‚ฝ์งˆ์„ ๋”ํ•ด ์„ฑ๊ณต ๐Ÿ˜ญ

 

๋ฌธ์ œ ์ •๋ณด

์Šคํƒ ์‹ค๋ฒ„2 1h32m x

์„ค๊ณ„ ๋ฐฉ๋ฒ•

๋‚˜์˜ ํ’€์ด

cursor์˜ ๋ฒ”์œ„๋ฅผ 0๋ถ€ํ„ฐ len(str)๊นŒ์ง€๋กœ ์žก๊ณ  if๋ฌธ์„ ํ™œ์šฉํ•˜์—ฌ ๊ฐ cmd ๋งˆ๋‹ค ์ƒํ™ฉ์— ๋งž๊ฒŒ ํ•ด๊ฒฐ

 

์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ์ผ์–ด๋‚˜์ง€ ์•Š์€ ๋‹ค๋ฅธ ํ’€์ด

  1. sys.stdin.readline()์„ ์“ฐ๊ธฐ ์œ„ํ•ด์„œ import sys.
  2. 2๊ฐœ์˜ ์Šคํƒ์„ ์ด์šฉํ•˜์—ฌ ์ปค์„œ๊ฐ€ ์›€์ง์ผ ๋•Œ ๋งˆ๋‹ค ์–‘ ์Šคํƒ์— append or pop → remove, insert์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„ O(n)/ stack์˜ push, pop ์‹œ๊ฐ„๋ณต์žก๋„ O(1)
  3. ์Šคํƒ ์™ผ์ชฝ์„ ํ‘œํ˜„ํ•œ st1 ๋ณ€์ˆ˜์— ๋ฌธ์ž ์ž…๋ ฅ ๋ฐ›์Œ
  4. ์Šคํƒ ์˜ค๋ฅธ์ชฝ์„ ํ‘œํ˜„ํ•œ st2 ๋ณ€์ˆ˜์— ์Šคํƒ์„ ์Œ“๊ธฐ ์œ„ํ•ด ๋นˆ ๋ฆฌ์ŠคํŠธ ์ดˆ๊ธฐํ™” ํ›„ ์‹œ์ž‘
  5. ์ปค์„œ๊ฐ€ ์™ผ์ชฝ์œผ๋กœ ์›€์ง์ด๋ฉด st2.append(st1.pop()), ์ปค๊ฑฐ๊ฐ€ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์›€์ง์ด๋ฉด st1.append(st2.pop()) ์ด๋Ÿฐ์‹์œผ๋กœ ๊ตฌํ˜„

๐Ÿ“ ์ฃผ์˜. ๋งˆ์ง€๋ง‰์— st1๊ณผ st2๋ฅผ ํ•ฉ์น  ์‹œ st2.reverse()๋กœ ํ•˜๋ฉด st2๊ฐ€ ๋น„์–ด์žˆ์„๋•Œ ํƒ€์ž…์—๋Ÿฌ๊ฐ€ ๋‚˜๊ธฐ ๋•Œ๋ฌธ์— reverse(st2)๋กœ ์ž‘์„ฑํ•  ๊ฒƒ

์ฝ”๋“œ

๋‚ด ์ฝ”๋“œ

str = input()
n = int(input())
cursor = len(str)

for _ in range(n):
  cmd = input().split()
  if cmd[0] == "L" and cursor != 0:
    cursor -=1
  elif cmd[0] == "D" and cursor != n:
    cursor +=1
  elif cmd[0] == "B":
    # remove
    str = str[:cursor-1]+str[cursor:]
    cursor -= 1
  elif cmd[0] == "P":
    # insert
    str = str[:cursor]+ cmd[1] + str[cursor:]
    cursor += 1

print(str)

์ •๋‹ต ์ฝ”๋“œ

import sys

st1 = list(input())
st2 = []
n = int(input())
for _ in range(n):
  cmd = sys.stdin.readline().split()
  if cmd[0] == 'L':
    if st1:
      st2.append(st1.pop())
  elif cmd[0] == 'D':
    if st2:
      st1.append(st2.pop())
  elif cmd[0] == 'B':
    if st1:
      st1.pop()
  else:
    st1.append(cmd[1])
st1.extend(reversed(st2))
print(''.join(st1))

์‹œ๊ฐ„ ๋ณต์žก๋„

$O(1)$

์–ด๋ ค์› ๋˜ ์ 

์‹œ๊ฐ„์ œํ•œ์ด 0.3์ดˆ๋กœ ๊ต‰์žฅํžˆ ์งง๊ฒŒ ์กด์žฌํ•˜์˜€์Œ → sys importํ•ด์™€์„œ ์‹œ๋„ํ–ˆ์ง€๋งŒ ์‹คํŒจ

sys ๋งจ๋‚  ๋ณต์‚ฌ ๋ถ™์–ด๋„ฃ๊ธฐ๋งŒ ํ•˜๊ณ  ๊ฐœ๋…์„ ์ œ๋Œ€๋กœ ๋ชฐ๋ผ์„œ ํ—ค๋งธ์Œ

์ฐธ๊ณ  ์ž๋ฃŒ

[๋ฐฑ์ค€] 1406๋ฒˆ ์—๋””ํ„ฐ - ํŒŒ์ด์ฌ(Python)

728x90