Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-unique-word-abbreviation.py 1.14 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-12 01:33 +08:00 . remove sensitive question description
# Time: O(2^n)
# Space: O(n)
class Solution(object):
def minAbbreviation(self, target, dictionary):
"""
:type target: str
:type dictionary: List[str]
:rtype: str
"""
def bits_len(target, bits):
return sum(((bits >> i) & 3) == 0 for i in xrange(len(target)-1))
diffs = []
for word in dictionary:
if len(word) != len(target):
continue
diffs.append(sum(2**i for i, c in enumerate(word) if target[i] != c))
if not diffs:
return str(len(target))
bits = 2**len(target) - 1
for i in xrange(2**len(target)):
if all(d & i for d in diffs) and bits_len(target, i) > bits_len(target, bits):
bits = i
abbr = []
pre = 0
for i in xrange(len(target)):
if bits & 1:
if i - pre > 0:
abbr.append(str(i - pre))
pre = i + 1
abbr.append(str(target[i]))
elif i == len(target) - 1:
abbr.append(str(i - pre + 1))
bits >>= 1
return "".join(abbr)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助