leetcode-820 单词的压缩编码 Python

方法一:存储后缀

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        s = set(words)
        for word in words:
            for i in range(1, len(word)):
                s.discard(word[i:])
        return sum(len(word) + 1 for word in s)

方法二:字典树

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        import collections
        from functools import reduce
        words = list(set(words))
        Trie = lambda: collections.defaultdict(Trie)
        trie = Trie()
        nodes = [reduce(dict.__getitem__, word[::-1], trie) for word in words]
        return sum(len(word)+1 for i, word in enumerate(words) if len(nodes[i]) == 0)

方法三:反转+排序

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        N = len(words)
        words_rev = []
        for word in words:
            words_rev.append(word[::-1])
        words_rev.sort()
        ans = 0
        for i in range(N):
            if i+1 < N and words_rev[i+1].startswith(words_rev[i]):
                pass
            else:
                ans += len(words_rev[i]) + 1    
        return ans

你可能感兴趣的:(leetcode-820 单词的压缩编码 Python)