【Lintcode】442. Implement Trie (Prefix Tree)

題目地址:

https://www.lintcode.com/problem/implement-trie-prefix-tree/description

實現字典樹Trie,題目保證所有字符串都由aza\sim z組成。由於題目保證所有字符串都由aza\sim z組成,所以對於Trie的Node類,它的next數組可以只開2626的長度。代碼如下:

public class Trie {
    
    class Node {
        boolean isWord;
        Node[] nexts;
        Node() {
            nexts = new Node[26];
        }
    }
    
    Node root;
    
    public Trie() {
        // do intialization if necessary
        root = new Node();
    }
    
    /*
     * @param word: a word
     * @return: nothing
     */
    public void insert(String word) {
        // write your code here
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.nexts[c - 'a'] == null) {
                cur.nexts[c - 'a'] = new Node();
            }
            cur = cur.nexts[c - 'a'];
        }
        
        cur.isWord = true;
    }
    
    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    public boolean search(String word) {
        // write your code here
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.nexts[c - 'a'] == null) {
                return false;
            }
            cur = cur.nexts[c - 'a'];
        }
        
        return cur.isWord;
    }
    
    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        // write your code here
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (cur.nexts[c - 'a'] == null) {
                return false;
            }
            cur = cur.nexts[c - 'a'];
        }
    
        return true;
    }
}

時間複雜度O(nl)O(nl)nn表示操作次數,ll表示字符串最長長度。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章