My java solution


  • 0
    H

    '''
    class TrieNode {
    // Initialize your data structure here.
    char ch;
    TrieNode[] children;
    boolean isEnd;

    public TrieNode() {
        this.children = new TrieNode[26];
        this.isEnd = false;
    }
    

    }

    public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    public void insert(String word) {
        int len = word.length();
        TrieNode temp = root;
        char ch;
        for(int i = 0; i < len;i++) {
            ch = word.charAt(i);
            if(temp.children[ch - 'a'] == null) {
                temp.children[ch - 'a'] = new TrieNode();
                temp.children[ch - 'a'].ch = ch;
                
            }
            temp = temp.children[ch - 'a'];
        }
        
        temp.isEnd = true;
        
    }
    
    // Returns if the word is in the trie.
    public boolean search(String word) {
        char ch;
        TrieNode temp = root;
        for(int i = 0; i < word.length(); i++) {
            ch = word.charAt(i);
            if(temp.children[ch - 'a'] == null) {
                return false;
            }
            temp = temp.children[ch - 'a'];
        }
        return temp.isEnd;
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        char ch;
        TrieNode temp = root;
        for(int i = 0; i < prefix.length(); i++) {
           ch = prefix.charAt(i);
           if(temp.children[ch - 'a'] == null) {
               return false;
           }
            temp = temp.children[ch - 'a'];
        }
        return true;
    }
    

    }
    '''


Log in to reply
 

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