Accepted Java Solution


  • 0
    P

    class TrieNode {
    // Initialize your data structure here.
    int value;
    TrieNode[] children = new TrieNode[26];
    public TrieNode() {
    value = 0;
    for(int i = 0 ; i < 26 ; i++){
    this.children[i] = null;
    }
    }
    }

    public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    public void insert(String word) {
        int length = word.length();
        int index;
        int level;
        TrieNode pTrie = this.root;
        
        for(level = 0; level < length ; level++){
            index = (int) (word.charAt(level)) - (int)('a');
            if(pTrie.children[index] == null){
                pTrie.children[index] = new TrieNode();
            }
            pTrie = pTrie.children[index];
        }
        pTrie.value = 1 + (int) (Math.random()*100) ;
    }
    
    // Returns if the word is in the trie.
    public boolean search(String word) {
        int length = word.length();
        int level;
        int index;
        TrieNode pTrie = this.root;
        
        for(level = 0 ; level < length ; level++){
            index = (int) (word.charAt(level)) - (int)('a');
            if(pTrie.children[index] == null) {
                return false;
            }
            pTrie = pTrie.children[index];
        }
        if(pTrie.value == 0) return false;
        return true;
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        int length = prefix.length();
        int level;
        int index;
        TrieNode pTrie = this.root;
        
        for(level = 0 ; level <length ; level++){
            index = (int) (prefix.charAt(level)) - (int)('a');
        if(pTrie.children[index] == null) {
                return false;
            }
            pTrie = pTrie.children[index];
        }
        if(pTrie.value != 0) return true;
        return true;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.