Please point out the mistake in this solution


  • 0
    T

    Fails the last test case.

    class TrieNode {
        // Initialize your data structure here.
        boolean isLast;
        Map<Character,TrieNode> map;
        public TrieNode() {
            isLast = false;
            map = new HashMap<Character,TrieNode>();
        }
        
        public boolean containsCharacter(char c){
            return map.containsKey(c);
        }
        
        public void addCharacter(char c){
            map.put(c, new TrieNode());
        }
        
        public TrieNode getNextNode(char c){
            return map.get(c);
        }
        
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode temp = root;
            for(int i = 0;i<word.length();i++){
                char c = word.charAt(i);
                if(i==word.length()-1 && !temp.isLast){
                    temp.isLast = true;
                }
                if( temp.containsCharacter(c) ){
                    temp = temp.getNextNode(c);
                }
                else{
                    temp.addCharacter(c);
                    temp = temp.getNextNode(c);
                }
                
            }
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode temp = root;
            
            for(int i = 0;i<word.length();i++){
                char c = word.charAt(i);
                if(!temp.containsCharacter(c)) return false;
                if(i== word.length()-1 && !temp.isLast) return false;
                temp = temp.getNextNode(c);
            }
            
            return true;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode temp = root;
            
            for(int i = 0;i<prefix.length();i++){
                char c = prefix.charAt(i);
                if(!temp.containsCharacter(c)) return false;
                temp = temp.getNextNode(c);
            }
            return true;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");

Log in to reply
 

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