411. Minimum Unique Word Abbreviation
利用比较基本的方法,backtracking找出全部的abbreviation,TLE
class Solution(object):
def minAbbreviation(self, target, dictionary):
"""
:type target: str
:type dictionary: List[str]
:rtype: str
"""
# 基本想法是先把dict里的所有可能的变形都找出来
# 然后再找target
res = set()
if dictionary:
for word in dictionary:
self.search(word, "", 0, 0, res)
if not res:
return str(len(target))
target_set = set()
self.search(target, "", 0, 0, target_set)
new = target_set.difference(res)
return sorted(new, key=self.cal)[0]
def cal(self, s):
l = 0
first_digit = True
for c in s:
if first_digit and c.isdigit():
l += 1
first_digit = False
if not c.isdigit():
l += 1
first_digit = True
return l
def search(self, s, cur, pos, count, res):
if pos == len(s):
if count > 0:
cur += str(count)
res.add(cur)
return
self.search(s, cur, pos+1, count+1, res) # 缩略当前的字母增加count
if count > 0:
cur = cur + str(count) + s[pos]
else:
cur = cur + s[pos]
self.search(s, cur, pos+1, 0, res)
网友评论