We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Essentially you are looking for an overlap of any letter with the end of any word, so most of the code is just implementing a Trie, which is missing in Java
publicstaticvoidnoPrefix(List<String>words){//Sorting would make this faster, but their examples show we would reach the wrong result if sortedTrietrie=newTrie();for(Stringword:words){//System.out.println("Add " + word + " to trie of size " + trie.size());if(trie.add(word)){//overlap detectedSystem.out.println("BAD SET");System.out.println(word);return;}}System.out.println("GOOD SET");}staticclassTrieextendsHashMap<Character,TrieNode>{/* returns true if an overlap is detected */publicbooleanadd(Stringword){charc=word.charAt(0);TrieNoden=get(c);if(n==null){//System.out.println("=> Adding " + c + (word.length() == 1? " (Word End)":" (Node)"));n=newTrieNode(word);put(c,n);returnfalse;//its a new node it cant be an overlap}else{//System.out.println("=> Updating " + c);//We already have the first char as n, so just try the restif(word.length()>1){returnn.add(word.substring(1));}else{n.isWordEnd=true;//its a word end now since we reached finalletter of a word}}returnn.isWordEnd;}}staticclassTrieNode{booleanisWordEnd=false;Triebranch=null;charc;publicTrieNode(charc,booleanisWordEnd){this.c=c;this.isWordEnd=isWordEnd;}publicTrieNode(Stringc){this(c.charAt(0),c.length()==1);if(c.length()>1){add(c.substring(1));}}/* method assumes, this is letters after c, that c is already trimmed *//* returns true if an overlap is detected */publicbooleanadd(Stringword){if(branch==null){branch=newTrie();}//System.out.println("=> Add " + word.charAt(0) + " after " + c);returnisWordEnd||branch.add(word);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
No Prefix Set
You are viewing a single comment's thread. Return to all comments →
Essentially you are looking for an overlap of any letter with the end of any word, so most of the code is just implementing a Trie, which is missing in Java