# 208 Implement Trie

Trie就是字典樹。

每個TrieNode有26個child,用TrieNode[] child表示。

以圖片為例,root node有26個child(不考慮大小寫的情況),除了t,a,i以外的child node都為null。表示這個字典裡只有t,a,i開頭的字。

再往下到t node,26個child中只有o,e不是null。表示字典裡只有to,te開頭的字。

題目要我implement search(), insert()和startsWith(),

實作三個function之前,要先create TrieNode class, 裡面要有char val, char[] child, boolean isWord,

Pseudocode:

/** Inserts a word into the trie. */
    public void insert(String word) {
        /*
        for each character in word,
            if current TrieNode's child[c] is null
                new TrieNode for child[c]
            else
                current TrieNode = child[c]
        set isWord of the last node to true
        */
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        /*
        for each char in word,
            if currentNode's child[c] != null
                continue;
            else
                return false
            currentNode = child[c]
        return currentNode.isWord;
        */
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        /*
        for each char in prefix,
            if current TrieNode's child[c] != null
                continue;
            else
                return false
            currentNode = child[c]
        return true;
        */
    }
}

完整程式碼

class TrieNode {
    public char val;
    public boolean isWord; 
    public TrieNode[] children = new TrieNode[26];
    public TrieNode() {}
    TrieNode(char c){
        TrieNode node = new TrieNode();
        node.val = c;
    }
}

public class Trie {
    private TrieNode root;
    public Trie() {
        root = new TrieNode();
        root.val = ' ';
    }

    public void insert(String word) {
        TrieNode ws = root;
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(ws.children[c - 'a'] == null){
                ws.children[c - 'a'] = new TrieNode(c);
            }
            ws = ws.children[c - 'a'];
        }
        ws.isWord = true;
    }

    public boolean search(String word) {
        TrieNode ws = root; 
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(ws.children[c - 'a'] == null) return false;
            ws = ws.children[c - 'a'];
        }
        return ws.isWord;
    }

    public boolean startsWith(String prefix) {
        TrieNode ws = root; 
        for(int i = 0; i < prefix.length(); i++){
            char c = prefix.charAt(i);
            if(ws.children[c - 'a'] == null) return false;
            ws = ws.children[c - 'a'];
        }
        return true;
    }
}

results matching ""

    No results matching ""