๋ฐฑ์ค (BOJ) 1406๋ฒ
https://www.acmicpc.net/problem/1406
์ฌ์ฉ์ธ์ด : PYTHON
1.๋ฌธ์
2.ํ์ด
์๊ฐ๋ณต์ก๋๋ฅผ ๊ณ ๋ คํด์ผํ๋ ๋ฌธ์ ์๋ค.
์ฒ์์๋ ํ์ฌ ์ปค์์ ์์น๋ฅผ ์ ์ฅํ๋ cursor
๋ณ์์, ๋ฆฌ์คํธ์ insert
, del
๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋๋ฐ ์ด๋ ๊ฒ ํ๋ ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค. ๋ ๋ฉ์๋์ ์๊ฐ๋ณต์ก๋๊ฐ O(n)
์ด๊ณ , ์ด๊ฒ์ m
๋ฒ ๋ฐ๋ณตํ๊ธฐ ๋๋ฌธ์ด์๋ค.
์ด ์๊ฐ์ด๊ณผ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์ ์๊ฐ๋ณต์ก๋๊ฐ O(1)์ธ pop()
๊ณผ append()
์ฐ์ฐ์ ์ฌ์ฉํด์ผ ํ๋ค. ๊ทธ๋ฆฌ๊ณ cusor๋ณ์๋ฅผ ๋ ๊ฐ์ ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํด์ ๊ตฌํํ ์ ์์๋ค.
์ปค์๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฆฌ์คํธ st
์ tmp_st
๋ก ๋๋์๋ค. ์ปค์๋ฅผ ์ผ์ชฝ์ผ๋ก ์ฎ๊ธฐ๋ฉด st
์์ pop()ํ์ฌ tmp_st
์ append(), ์ปค์๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก ์ฎ๊ธฐ๋ฉด tmp_st
์์ pop()ํ์ฌ st
์ append()
๋ชจ๋ ์ฐ์ฐ์ด ์ํ ๋ ์ดํ์๋, tmp_st์ ๋ฌธ์์ด๋ค์ด ๊ฑฐ๊พธ๋ก ์ ์ฅ๋์ด ์์ผ๋ฏ๋ก, tmp_st๋ฅผ reversed()ํ ํ extendํ์ฌ st์ ํฉ์ณ์ฃผ๊ณ , ''.join์ ์ฌ์ฉํ์ฌ ๋ฌธ์์ด๋ก ์ถ๋ ฅํ์๋ค.
3.์ฝ๋
3-1.์๊ฐ์ด๊ณผ ์ฝ๋
import sys
input = sys.stdin.readline
st=list(input().rstrip())
cursor=len(st)
m=int(input())
for _ in range(m):
command=input().split()
if command[0]=='P':
st.insert(cursor,command[1])
cursor+=1
elif command[0]=='L' and cursor!=0:
cursor-=1
elif command[0]=='D' and cursor!=len(st):
cursor+=1
elif command[0]=='B' and cursor!=0:
del st[cursor-1]
cursor-=1
print(''.join(st))
3-2.์ ๋ต์ฝ๋
import sys
input = sys.stdin.readline
st=list(input().rstrip())
m=int(input())
tmp_st=[]
for _ in range(m):
cmd=input().split()
if cmd[0]=='L' and len(st)>0:
tmp_st.append(st.pop())
elif cmd[0]=='D' and len(tmp_st)>0:
st.append(tmp_st.pop())
elif cmd[0]=='B' and len(st)>0:
st.pop()
elif cmd[0]=='P':
st.append(cmd[1])
st.extend(reversed(tmp_st))
print(''.join(st))
'๐์ฝ๋ฉํ ์คํธ:CodingTest' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค 6588๋ฒ-ํ์ด์ฌ]๊ณจ๋๋ฐํ์ ์ถ์ธก (0) | 2023.06.20 |
---|---|
[๋ฐฑ์ค 17298๋ฒ-ํ์ด์ฌ]์คํฐ์ (0) | 2023.06.20 |
[๋ฐฑ์ค 18870๋ฒ-ํ์ด์ฌ]์ขํ์์ถ (0) | 2023.06.20 |
[๋ฐฑ์ค 2108๋ฒ-ํ์ด์ฌ]ํต๊ณํ (0) | 2023.06.20 |
[๋ฐฑ์ค 1181๋ฒ-ํ์ด์ฌ]๋จ์ด ์ ๋ ฌ (0) | 2023.06.19 |