Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
74 lines (62 loc) · 2.04 KB

208.md

File metadata and controls

74 lines (62 loc) · 2.04 KB

208. Implement Trie (Prefix tree)

Description

Implement a trie with insert, search, and startsWith methods

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

public class Trie {
    TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode currentNode = root;
        for(int i = 0; i < word.length(); i++){
            int charPosition = word.charAt(i) - 'a';
            if(currentNode.children[charPosition] != null){
                currentNode = currentNode.children[charPosition];
            }else{
                currentNode.children[charPosition] = new TrieNode();
                currentNode = currentNode.children[charPosition];
            }
        }
        currentNode.isEndOfWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode currentNode = root;
        
        for(int i = 0; i < word.length(); i++){
            int charPosition = word.charAt(i) - 'a';
            if(currentNode.children[charPosition] != null){
                currentNode = currentNode.children[charPosition];
            }else{
                return false;
            }
        }
        return currentNode.isEndOfWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode currentNode = root;
        
        for(int i = 0; i < prefix.length(); i++){
            int charPosition = prefix.charAt(i) - 'a';
            if(currentNode.children[charPosition] != null){
                currentNode = currentNode.children[charPosition];
            }else{
                return false;
            }
        }
        return true;
    }
}

class TrieNode{
    TrieNode[] children;
    boolean isEndOfWord;
    
    TrieNode(){
        children = new TrieNode[26];
        isEndOfWord = false;
    }
}