1. 程式人生 > 資訊 >6299 元,小米 MIX 4 三體聯名禮盒限量款今日上市:全球限量 500 套

6299 元,小米 MIX 4 三體聯名禮盒限量款今日上市:全球限量 500 套

Trie(發音類似 "try")或者說 字首樹 是一種樹形資料結構,用於高效地儲存和檢索字串資料集中的鍵。這一資料結構有相當多的應用情景,例如自動補完和拼寫檢查。

請你實現 Trie 類:

Trie() 初始化字首樹物件。
void insert(String word) 向前綴樹中插入字串 word 。
boolean search(String word) 如果字串 word 在字首樹中,返回 true(即,在檢索之前已經插入);否則,返回 false 。
boolean startsWith(String prefix) 如果之前已經插入的字串word 的字首之一為 prefix ,返回 true ;否則,返回 false 。

示例:

輸入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
輸出
[null, null, true, false, true, null, true]

解釋
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

 public class TrieNode{
        public int pass;
        public int end;
        public TrieNode[] nexts=new TrieNode[26];
    }

    public TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root=new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if(word==null){
            return;
        }
        TrieNode node=root;
        node.pass++;
        char[] chs=word.toCharArray();
        int index=0;
        for(int i=0;i<chs.length;i++){
            index=chs[i]-'a';
            if(node.nexts[index]==null){
                node.nexts[index]=new TrieNode();
            }
            node=node.nexts[index];
            node.pass++;
        }
        node.end++;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        if(word==null){
            return false;
        }
        TrieNode node=root;
        char[] chs=word.toCharArray();
        int index;
        for(int i=0;i<chs.length;i++){
            index=chs[i]-'a';
            if(node.nexts[index]==null){
                return false;
            }
            node=node.nexts[index];
        }
        return node.end>0;

    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        if(prefix==null){
            return false;
        }
        TrieNode node=root;
        char[] chs=prefix.toCharArray();
        int index;
        for(int i=0;i<chs.length;i++){
            index=chs[i]-'a';
            if(node.nexts[index]==null){
                return false;
            }
           node= node.nexts[index];
        }
        return true;
    }
}