leetcode之820. 單詞的壓縮編碼 | python極簡實現字典樹


題目

給定一個單詞列表,我們將這個列表編碼成一個索引字符串 S 與一個索引列表 A。

例如,如果這個列表是 ["time", "me", "bell"],我們就可以將其表示為 S = "time#bell#" 和 indexes = [0, 2, 5]。

對於每一個索引,我們可以通過從字符串 S 中索引的位置開始讀取字符串,直到 "#" 結束,來恢復我們之前的單詞列表。

那么成功對給定單詞列表進行編碼的最小字符串長度是多少呢?

示例:

輸入: words = ["time", "me", "bell"]
輸出: 10
說明: S = "time#bell#" , indexes = [0, 2, 5] 。

提示:

1 <= words.length <= 2000
1 <= words[i].length <= 7
每個單詞都是小寫字母 。

https://leetcode-cn.com/problems/short-encoding-of-words

今天leetcode的每日一題的官方題解的python解法驚艷到我了,代碼十分Pythonic,正好我也不太熟悉字典樹和reduce的用法,學了一下:
簡單的來說就是:一句話實現字典樹,一句話完成建樹過程。

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        words = list(set(words)) #remove duplicates
        #Trie is a nested dictionary with nodes created
        # when fetched entries are missing
        Trie = lambda: collections.defaultdict(Trie)
        trie = Trie()

        #reduce(..., S, trie) is trie[S[0]][S[1]][S[2]][...][S[S.length - 1]]
        nodes = [reduce(dict.__getitem__, word[::-1], trie)
                 for word in words]

        #Add word to the answer if it's node has no neighbors
        return sum(len(word) + 1
                   for i, word in enumerate(words)
                   if len(nodes[i]) == 0)

Trie = lambda: collections.defaultdict(Trie)這個循環嵌套字典是類似這樣的效果{{{{}}}},意思是只要沒有key的我們就返回一個空字典。
其實字典樹的本質就是循環嵌套字典。
trie[word[-1]][word[-2]].........是寫成這樣了reduce(dict.__getitem__, word[::-1], trie)

下面給出@Lucien在leetcode題解下的評論解釋
關於Python字典樹方法的解釋:

我們需要一棵字典樹,把所有word加入這棵樹
找到所有葉子的高度和
一步步從最正常的寫法走向Pythonic的解。

# 定義字典樹中的一個節點
class Node(object):
    def __init__(self):
        self.children={}
class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        words = list(set(words)) #需要去重,否則在之后計算“葉子高度”的時候會重復計算
        trie=Node() #這是字典樹的根
        nodes=[] #這里保存着每個word對應的最后一個節點,比如對於單詞time,它保存字母t對應的節點(因為是從后往前找的)
        for word in words:
            now=trie
            for w in reversed(word):
                if w in now.children:
                    now=now.children[w]
                else:
                    now.children[w]=Node()
                    now=now.children[w]
            nodes.append(now)
        ans=0
        for w,c in zip(words,nodes):
            if len(c.children)==0: #沒有children,意味着這個節點是個葉子,nodes保存着每個word對應的最后一個節點,當它是一個葉子時,我們就該累加這個word的長度+1,這就是為什么我們在最開始要去重
                ans+=len(w)+1
        return ans

相信以上的解答大家可以看懂,那么就從Node開始簡化。原先我們把Node聲明為一個類,但這個類中只有一個字典,所以我們不如就直接用一個字典來表示節點,一個空字典以為着這是一個葉子節點,否則字典中的每一個元素都是它的一個孩子,上面的代碼可以簡化為:

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        words = list(set(words)) #需要去重,否則在之后計算“葉子高度”的時候會重復計算
        trie={} #這是字典樹的根
        nodes=[] #這里保存着每個word對應的最后一個節點,比如對於單詞time,它保存字母t對應的節點(因為是從后往前找的)
        for word in words:
            now=trie
            for w in reversed(word):
                if w in now:
                    now=now[w]
                else:
                    now[w]={}
                    now=now[w]
            nodes.append(now)
        ans=0
        for w,c in zip(words,nodes):
            if len(c)==0: #一個空字典,意味着這個節點是個葉子
                ans+=len(w)+1
        return ans

繼續簡化,我們不想在生成字典樹時每次都判斷“當前字典有沒有這個鍵”,我們希望,有這個鍵,就返回它的值,否則返回一個空字典給我。很自然,我們需要用到defaultdict,它默認返回一個字典。但,只是返回一個普通字典嗎?比如defaultdict(dict)? 不行,實際上它需要返回一個defaultdict,且這個defaultdict仍舊會遞歸地返回defaultdict。於是,遞歸地,我們定義這樣一個函數,它返回一個defaultdict類型,且它的默認值是該類型本身。 Trie = lambda: collections.defaultdict(Trie) ,注意,這里的Trie是一個函數,它返回一個defaultdict實例。有了它,我們創建字典樹的過程就變成了:

nodes=[]
Trie = lambda: collections.defaultdict(Trie)
trie = Trie()
for word in words:
    now=trie
    for w in word[::-1]:
        now=now[w]
    nodes.append(now)

更進一步,可以簡化為

nodes=[]
Trie = lambda: collections.defaultdict(Trie)
trie = Trie()
for word in words:
    nodes.append(trie[word[-1]][word[-2]].........)

它就變成了

nodes = [reduce(dict.__getitem__, word[::-1], trie)
                 for word in words]

先不管數組的推導式,單看數組的一項 reduce(dict.getitem, word[::-1], trie),reduce三個參數分別為:方法,可循環項,初始值。即它初始值是trie,按照word[::-1]的循環順序,每次去執行方法dict.getitem,且將這個輸出作為下次循環的輸入,所以它就是trie[word[-1]][word[-2]].........的意思。

最后一步的sum很簡單,只要大家明白nodes里存的是什么就很明顯了。

另外附上標准的C++寫法:

class TrieNode{
    TrieNode* children[26];
public:
    int count;
    TrieNode() {
        for (int i = 0; i < 26; ++i) children[i] = NULL;
        count = 0;
    }
    TrieNode* get(char c) {
        if (children[c - 'a'] == NULL) {
            children[c - 'a'] = new TrieNode();
            count++;
        }
        return children[c - 'a'];
    }
};
class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        TrieNode* trie = new TrieNode();
        unordered_map<TrieNode*, int> nodes;

        for (int i = 0; i < (int)words.size(); ++i) {
            string word = words[i];
            TrieNode* cur = trie;
            for (int j = word.length() - 1; j >= 0; --j)
                cur = cur->get(word[j]);
            nodes[cur] = i;
        }

        int ans = 0;
        for (auto& [node, idx] : nodes) {
            if (node->count == 0) {
                ans += words[idx].length() + 1;
            }
        }
        return ans;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM