Tire Time limit exceeded


  • 0
    J
    class TrieNode {
    // Initialize your data structure here.
    HashMap<Character, TrieNode> children;
    boolean isLeaf;
    public TrieNode() {
        children=new HashMap<>();
        isLeaf=false;
    }
    

    }

    public class Trie {
    private TrieNode root=new TrieNode();

    public Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    public void insert(String word) {
        
        if (word.length()==0)
            return;
        
        TrieNode node= root;
        int n=word.length();
        for (int i=0;i<n;i++){
            char c=word.charAt(0);
            if (node.children.containsKey(c))
                node=node.children.get(c);
            else{
                TrieNode newNode=new TrieNode();
                node.children.put(c,newNode);
                node=newNode;
            }
            if (word.length()>1)
                word=word.substring(1);
            else
                node.isLeaf=true;
        }
    }
    
    // Returns if the word is in the trie.
    public boolean search(String word) {
        if (word.length()==0)
            return true;
        TrieNode node= root;
        int n=word.length();
        for (int i=0;i<n;i++){
            if (node.children.containsKey(word.charAt(0)))
                if (word.length()==1){
                    node=node.children.get(word.charAt(0));
                    if (node.isLeaf)
                        return true;
                    else return false;
                }
                else{
                    node=node.children.get(word.charAt(0));
                    word=word.substring(1);
                }
            else
                return false;
        }
        return false;
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if (prefix.length()==0)
            return true;
        TrieNode node= root;
        int n=prefix.length();
        for (int i=0;i<n;i++){
            if (node.children.containsKey(prefix.charAt(0)))
                if (prefix.length()==1)
                    if (node.isLeaf==false)
                        return true;
                    else return false;
                else{
                    node=node.children.get(prefix.charAt(0));
                    prefix=prefix.substring(1);
                }
            else
                return false;
        }
        return false;
    }
    

    }

    I always receive time limit exceeded. Can anyone tell me what is wrong?
    Thanks!


  • 0

    Please try submitting again, I've just extended the time limit.


Log in to reply
 

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