No Prefix Set

  • + 0 comments

    Java

    	TrieNode root = new TrieNode();
            
            for(String word : words){
                TrieNode curr = root;
                boolean nodeAdded = false;
    						
                for(int j=0; j<word.length(); j++){
                    if(curr.isWord){
    			//Found prefix in the tree
                        System.out.println("BAD SET");
                        System.out.println(word);
                        return;
                    } 
    								
    		if(!curr.children.containsKey(word.charAt(j))){
                        curr.children.put(word.charAt(j), new TrieNode());
                        nodeAdded = true;
                    }
                    curr = curr.children.get(word.charAt(j));
                }
                curr.isWord = true;
                if(!nodeAdded){
    		//No new node added means the word is a prefix
                    System.out.println("BAD SET");
                    System.out.println(word);
                    return;
                }
            }
            System.out.println("GOOD SET");