LeetCode 208.實(shí)現(xiàn) Trie (前綴樹) (Implement Trie (Prefix Tree))

LeetCode.jpg

208. 實(shí)現(xiàn) Trie (前綴樹)

實(shí)現(xiàn)一個(gè) Trie (前綴樹),包含 insert, search, 和 startsWith 這三個(gè)操作。

示例:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
說(shuō)明:

你可以假設(shè)所有的輸入都是由小寫字母 a-z 構(gòu)成的。
保證所有輸入均為非空字符串。
在真實(shí)的面試中遇到過這道題?

Python3 實(shí)現(xiàn)

# @author:leacoder 
# @des:  實(shí)現(xiàn) Trie (前綴樹)
class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}
        self.endofword = "end"

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        node = self.root
        for char in word:
            # dict.setdefault(key, default=None) 如果 key 在 字典中,返回對(duì)應(yīng)的值。
            # 如果不在字典中,則插入 key 及設(shè)置的默認(rèn)值 default,并返回 default ,default 默認(rèn)值為 None。
            node = node.setdefault(char,{}) 
            
        node[self.endofword] = self.endofword

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        node = self.root
        for char in word:
            if char not in node:
                return False
            #node = node[char]
            node = node.get(char)
        return self.endofword in node
        

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        node = self.root
        for char in prefix:
            if char not in node:
                return False
            #node = node[char]
            node = node.get(char)
        return True

Java 實(shí)現(xiàn)

/*
 *@author:leacoder
 *@des:  實(shí)現(xiàn) Trie (前綴樹)
 */
class Trie {
    
    public int SIZE = 26;
    public TrieNode root;
    
    class TrieNode {
        
        TrieNode(char c){
            this.val = c;
            this.isWord = false;
            this.child = new TrieNode[SIZE];
        }
        
        public char val;
        public boolean isWord;
        public TrieNode[] child ;
    }
    
    

    /** Initialize your data structure here. */
    public Trie() {
        this.root = new TrieNode(' ');
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if(word == null || word.length() == 0) return;
        TrieNode node = this.root;
        for( int i = 0; i < word.length(); i++ ){
            char c = word.charAt(i);
            if( node.child[c - 'a'] == null){
                node.child[c - 'a'] = new TrieNode(c);
            } 
            node = node.child[c - 'a'];
        }
        node.isWord = true;
        
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = this.root;
        for( int i = 0; i < word.length(); i++ ){
            char c = word.charAt(i);
            if( node.child[c - 'a'] == null){
                return false;
            }
            node = node.child[c - 'a'];
        }
        
        return node.isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        
        TrieNode node = this.root;
        for( int i = 0; i < prefix.length(); i++ ){
            char c = prefix.charAt(i);
            if( node.child[c - 'a'] == null){
                return false;
            }
            node = node.child[c - 'a'];
        }
        
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

GitHub鏈接:
https://github.com/lichangke/LeetCode
知乎個(gè)人首頁(yè):
https://www.zhihu.com/people/lichangke/
簡(jiǎn)書個(gè)人首頁(yè):
http://www.itdecent.cn/u/3e95c7555dc7
個(gè)人Blog:
https://lichangke.github.io/
歡迎大家來(lái)一起交流學(xué)習(xí)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容