1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
word-abbreviation.py 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . add complexity
# Time: O(n * l) ~ O(n^2 * l^2)
# Space: O(n * l)
import collections
class Solution(object):
def wordsAbbreviation(self, dict):
"""
:type dict: List[str]
:rtype: List[str]
"""
def isUnique(prefix, words):
return sum(word.startswith(prefix) for word in words) == 1
def toAbbr(prefix, word):
abbr = prefix + str(len(word) - 1 - len(prefix)) + word[-1]
return abbr if len(abbr) < len(word) else word
abbr_to_word = collections.defaultdict(set)
word_to_abbr = {}
for word in dict:
prefix = word[:1]
abbr_to_word[toAbbr(prefix, word)].add(word)
for abbr, conflicts in abbr_to_word.iteritems():
if len(conflicts) > 1:
for word in conflicts:
for i in xrange(2, len(word)):
prefix = word[:i]
if isUnique(prefix, conflicts):
word_to_abbr[word] = toAbbr(prefix, word)
break
else:
word_to_abbr[conflicts.pop()] = abbr
return [word_to_abbr[word] for word in dict]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助