입출력 예시
keymap | targets | result |
["ABACD", "BCEFD"] | ["ABCD","AABB"] | [9, 4] |
["AA"] | ["B"] | [-1] |
["AGZ", "BSSS"] | ["ASA","BGZ"] | [4, 6] |
나의 코드
def solution(keymap, targets):
answer = []
chrs = set(''.join(keymap))
chr_dict = dict()
for c in chrs:
min_n = 100
for key in keymap:
temp = key.find(c)
if temp != -1 and temp < min_n:
min_n = temp
chr_dict[c] = min_n+1
for st in targets:
min_m = 0
for c in st:
try:
min_m += chr_dict[c]
except:
min_m = -1
break
answer.append(min_m)
return answer
Python
복사
다른 풀이
# by YeoEunSeong
def solution(keymap, targets):
answer = []
hs = {}
for k in keymap:
for i, ch in enumerate(k):
hs[ch] = min(i + 1, hs[ch]) if ch in hs else i + 1
for i, t in enumerate(targets):
ret = 0
for ch in t:
if ch not in hs:
ret = - 1
break
ret += hs[ch]
answer.append(ret)
return answer
Python
복사
개선점 분석
•
dictionary 만들 때 좀 더 간단하게 만들기
•
dictionary 이므로 try except 구문 대신 not in 등으로 체크