美文网首页
8.23 - hard - 100

8.23 - hard - 100

作者: 健时总向乱中忙 | 来源:发表于2017-08-24 10:16 被阅读0次

527. Word Abbreviation

基本的想法就是先计算出所有的abbr,然后把相同的abbr的index记录下来,然后依次扩展直到这一位消除了所有的相同的,这个video简直是神解释:https://www.youtube.com/watch?v=yAQMcGY4c90

class Solution(object):
    def wordsAbbreviation(self, dict):
        """
        :type dict: List[str]
        :rtype: List[str]
        """
        def get_abbreviation(word,old_abbreviation):
            if old_abbreviation == '':
                abbreviation = word[0] + str(len(word[1:-1])) + word[-1]                
            else:
                for i in range(len(old_abbreviation)):
                    if old_abbreviation[i].isdigit():
                        abbreviation = word[:i+1] + str(len(word[i+1:-1])) + word[-1]
                        break
            if len(word) <= len(abbreviation):
                abbreviation = word
            return abbreviation
        
        
        abbreviations = [''] * len(words)
        duplicates = collections.defaultdict(list)
        for i,word in enumerate(words):
            abbreviations[i] = get_abbreviation(word,'')
            duplicates[abbreviations[i]] += i,
        
        for i in range(len(abbreviations)):
            if len(duplicates[abbreviations[i]]) == 1:
                continue
            else:
                while len(duplicates[abbreviations[i]]) > 1:
                    for index in duplicates[abbreviations[i]]:
                        abbreviation = get_abbreviation(words[index], abbreviations[index])
                        abbreviations[index] = abbreviation
                        duplicates[abbreviation] += index,
                        
        return abbreviations

相关文章

  • 8.23 - hard - 100

    527. Word Abbreviation 基本的想法就是先计算出所有的abbr,然后把相同的abbr的inde...

  • 8.23 - hard - 91

    472. Concatenated Words 利用Trie做出一个TLE的版本。其实简单的利用recursion...

  • 8.23 - hard - 95

    493. Reverse Pairs 值得一看的post https://discuss.leetcode.com...

  • 8.23 - hard - 96

    499. The Maze III 想法很简单,有点懒得写。在heap里存上 dist,path,cur_pos,...

  • 8.23 - hard - 97

    502. IPO 手撸成功,考虑到排序的话,可以多考虑考虑heap。

  • 8.23 - hard - 92

    480. Sliding Window Median 因为python没有那种hashheap的数据结构,所以要用...

  • 8.23 - hard - 94

    488. Zuma Game 对每一个s消除三个连续的球,然后对于每一个可以消除的位置进行搜索,取其最小值。这道题...

  • 8.23 - hard - 98

    514. Freedom Trail 手写了TLE版本,加了一些memory,不过还是TLE。基本思路是对的,只是...

  • 8.23 - hard - 99

    517. Super Washing Machines这题挺诡异的,不用到什么数据结构,用到一些数学想法。其中一种...

  • 8.23 - hard - 93

    483. Smallest Good Base一道数学题,证明在这里。https://discuss.leetco...

网友评论

      本文标题:8.23 - hard - 100

      本文链接:https://www.haomeiwen.com/subject/rrmsdxtx.html