Simple Java Solution


  • 0
    T
    class TrieNode {
        // Initialize your data structure here.
        char c;
        ArrayList<TrieNode> children;
        boolean word=false;
        public TrieNode(char val) {
            c = val;
            children = new ArrayList();
        }
        
        public TrieNode() {
            c='\u0000';
            children = new ArrayList();
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode a = root, b;
            
            for(char c : word.toCharArray()){
                b = getNode(a,c);
                if(b==null){
                    TrieNode n = new TrieNode(c);
                    a.children.add(n);
                    a=n;
                }
                else{
                    a=b;
                }
            }
            a.word=true;
        }
        
        private TrieNode getNode(TrieNode parent, char c){
            if(parent.children.size()==0)return null;
            for(TrieNode t : parent.children){
                if(t.c==c){
                    return t;
                }
            }
            return null;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode a=root;
            for(char c : word.toCharArray()){
                a = getNode(a,c);
                if(a==null)return false;
            }
            return a.word;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
                    TrieNode a=root;
            for(char c : prefix.toCharArray()){
                a = getNode(a,c);
                if(a==null)return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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