from collections import deque
def dictionary() :
dic = {}
for i in range(1, 27) :
dic[chr(64+i)] = i
return dic
def solution(msg):
dic = dictionary()
idx = []
msg = deque(msg)
last = 26
w = msg.popleft()
d = True
while msg :
c = msg.popleft()
if w+c in dic :
while True :
w = w+c
try : c = msg.popleft()
except :
d = False
break
if w+c not in dic :
break
last += 1
dic[w+c] = last
idx.append(dic[w])
w = c
if d :
idx.append(dic[w])
return idx
풀이
1) 알파벳 사전 만들기
def dictionary() :
dic = {}
for i in range(1, 27) :
dic[chr(64+i)] = i
return dic
2) 메인 함수
def solution(msg):
dic = dictionary()
idx = []
msg = deque(msg)
last = 26
w = msg.popleft()
d = True
while msg :
c = msg.popleft()
if w+c in dic :
while True :
w = w+c
try : c = msg.popleft()
except :
d = False
break
if w+c not in dic :
break
last += 1
dic[w+c] = last
idx.append(dic[w])
w = c
if d :
idx.append(dic[w])
return idx
1. 들어오는 글자에서 두 개씩 뽑아 두 글자를 합쳤을 때, 그 글자가 사전에 있다면 한 글자를 더 가져와서 사전에 있는지 확인한다.
- 예) w = 'K', c = 'A' 인데, 'KA'가 사전에 있다면 'KAK'가 사전에 있는지 확인한다.
2. 합친 글자가 사전에 없다면 사전에 추가해주고, 해당 색인 번호를 idx 리스트에 추가해준다.
또한 다음 글자를 위해 c를 w로 대체해준다.
3. 마지막 남은 글자가 한글자일경우 --> d가 True인 경우.
바로 윗줄에서 c를 w로 대체해주었으니 w의 색인번호를 idx리스트에 추가해준다.
'Algorithm > Programmers' 카테고리의 다른 글
| [Python] 네트워크 (0) | 2021.06.20 |
|---|---|
| [Python] 소수 찾기 (0) | 2021.06.18 |
| [Python] 방금 그 곡 (0) | 2021.06.14 |
| [Python] 캐시 (0) | 2021.06.13 |
| [Python] 이진 변환 반복하기 (0) | 2021.06.13 |