Simple accepted JAVA solution


  • 0
    H

    I used recursion to handle the insert and search, where each function call the first character is removed from the word.

    public class Trie {
        Node root;
        
        public Trie() {
            root = new Node();
        }
        
        public void insert(String word) {
            root.insert(word);
        }
        
        public boolean search(String word) {
            return root.search(word, false);
        }
        
        public boolean startsWith(String prefix) {
            return root.search(prefix, true);
        }
    }
    
    class Node {
        Node[] nodes = new Node[26];
        boolean isLeaf = false;
        
        public Node() {}
        
        public void insert(String word) {
            if(word.length() == 0) {
                isLeaf = true;
                return;
            }
            int c = word.charAt(0)-'a';
            if(nodes[c] == null) nodes[c] = new Node();
            nodes[c].insert(word.substring(1,word.length()));
        }
        
        public boolean search(String word, boolean prefix) {
            if(word.length() == 0) return isLeaf||prefix;
            int c = word.charAt(0)-'a';
            if(nodes[c] == null) return false;
            return nodes[c].search(word.substring(1,word.length()), prefix);
        }
    }
    

Log in to reply
 

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