Easy to understand Java solution - beats 94.32% run time


  • 0
    K
    class TrieNode {
        TrieNode [] ptr;
        private boolean exists;
        public TrieNode() {
            ptr = new TrieNode[26];
            exists = false;
        }
        public void setExists(){
            exists = true;
        }
        public boolean getExists(){
            return exists;
        }
    }
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
        public void insert(String word) {
            TrieNode current = root;
            for(char c : word.toCharArray()){
                if(current.ptr[c - 'a'] == null)
                   current.ptr[c - 'a'] = new TrieNode();
                   current = current.ptr[c - 'a'];
            }
            current.setExists();
        }
        public boolean search(String word) {
            TrieNode current = root;
            for(char c : word.toCharArray()){
                if(current.ptr[c - 'a'] == null)
                   return false;
                   current = current.ptr[c - 'a'];
            }
            return current.getExists();
        }
        public boolean startsWith(String prefix) {
            TrieNode current = root;
            for(char c : prefix.toCharArray()){
                if(current.ptr[c - 'a'] == null)
                   return false;
                   current = current.ptr[c - 'a'];
            }
            return true;
        }
    }
    

Log in to reply
 

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