Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.

Note: You may assume that all inputs are consist of lowercase letters a-z.

Tips:

Trie的原理:tree的每一层代表单词的每个letter,每一层最多有26个node(26个字母),还有一个boolean用来store到此层位置是不是一个单词的结尾。

一定要先copy root。

Code:

class TrieNode {
    // Initialize your data structure here.
    TrieNode[] children;
    public boolean isKey;
    public TrieNode() {
        children = new TrieNode[26];
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode copy = root;
        for (int i = 0; i < word.length(); i++) {
            if (copy.children[word.charAt(i) - 'a'] == null) {
                copy.children[word.charAt(i) - 'a'] = new TrieNode();
                copy = copy.children[word.charAt(i) - 'a'];
            }
            else copy = copy.children[word.charAt(i) - 'a']; 
        }
        copy.isKey = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode copy = root;
        for (int i = 0; i < word.length(); i++) {
            if (copy.children[word.charAt(i) - 'a'] == null) {
                return false;
            }
            else copy = copy.children[word.charAt(i) - 'a'];
        }
        return copy.isKey;      
    }

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

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

results matching ""

    No results matching ""