Sunday 6 November 2016

Implement Trie (Prefix Tree) Leet Code Java Solution

Implement a trie with insertsearch, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.

Solution:-


class TrieNode {
   
    public TrieNode [] children;
    public boolean isLeaf;
    // Initialize your data structure here.
    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 temp = root;
        int length = word.length();
        for(int level = 0 ; level < length ; level ++){
           
            if(temp.children[word.charAt(level) - 'a'] == null){
                temp.children[word.charAt(level) - 'a'] = new TrieNode();
               
            }
            temp = temp.children[word.charAt(level) - 'a'];
           
        }
        temp.isLeaf = true;
    }

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

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

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

No comments:

Post a Comment