Tries

Trie data structure:

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

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode ptr=root;
        for(char a:word.toCharArray()){
            if(ptr.child[a-'a']==null){
                ptr.child[a-'a']=new TrieNode();
            }
            ptr=ptr.child[a-'a'];
        }
        ptr.isWord=true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode ptr=root;
        for(char a:word.toCharArray()){
            ptr=ptr.child[a-'a'];
            if(ptr==null) return false;
        }
        return ptr.isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode ptr=root;
        for(char a:prefix.toCharArray()){
            ptr=ptr.child[a-'a'];
            if(ptr==null) return false;
        }
        return true;
    }

    //Returns all the words that start in this prefix
    public List<String> searchPrefix(String prefix){
        List<String> res=new LinkedList<String>();
        TrieNode ptr=root;
        for(char a:prefix.toCharArray()){
            ptr=ptr.child[a-'a'];
            if(ptr==null) return res;
        }
        StringBuilder tmp=new StringBuilder(prefix);
        searchPrefixUtil(ptr,res,tmp);
        return res;
    }
    /* Depth First Traversal for a 26-ary tree*/
    public void searchPrefixUtil(TrieNode ptr, List<String> res, StringBuilder tmp){
        if(ptr.isWord) {
            res.add(tmp.toString());
            return;
        }
        for(int i=0;i<26;i++){
            if(ptr.child[i]!=null){
                tmp.append((char)('a'+i));
                searchPrefixUtil(ptr.child[i],res,tmp);
                tmp.deleteCharAt(tmp.length()-1);
            }
        }
    }
}

results matching ""

    No results matching ""