Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

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

Show Tags
Show Similar Problems

Have you met this question in a real interview? 

思路: Each TrieNode has a children with 26 TrieNode. When we want to insert or search a word from a TrieTree, we need to traverse the tree from root to leaf.

class TrieNode {
    // Initialize your data structure here.
    public char val;
    public TrieNode[] children = new TrieNode[26];
    public boolean isWord = false;
    public TrieNode() {
        
    }
    public TrieNode(char c){
        TrieNode node = new TrieNode();
        node.val = c;
    }
}

public class Trie {
    private TrieNode root;

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

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

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

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode curNode = root;
        for(int i = 0; i < prefix.length(); i++){
            if(curNode.children[prefix.charAt(i) - 'a'] == null)
                return false;
            curNode = curNode.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");


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