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.
Java 8 version (not type-safe(?))
simplified and updated thanks to @dgzwiro !
publicstaticfinalcharEND='_';publicstaticfinalStringBAD_SET_FORMAT="BAD SET\n%s";publicstaticvoidnoPrefix(List<String>words){// Write your code hereMap<Character,Object>trie=newHashMap<>();Map<Character,Object>current=null;// incremental insertion of wordsfor(Stringword:words){current=trie;// for each word, insert and change current map/dict per letterfor(charc:word.toCharArray()){// FAIL: a processed word is the prefix of the current wordif(current.containsKey(END)){System.out.printf(BAD_SET_FORMAT,word);return;}// create map/dict if missingif(!current.containsKey(c)){current.put(c,newHashMap<Character,Object>());}current=(HashMap<Character,Object>)current.get(c);}// FAIL: current word map/dict is not empty// meaning either:// - current word was already inserted in the trie// - current word was a prefix of previously inserted wordsif(!current.isEmpty()){System.out.printf(BAD_SET_FORMAT,word);return;}// mark the current node where the current word ends herecurrent.put(END,null);}System.out.println("GOOD SET");}
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 →
Java 8 version (not type-safe(?)) simplified and updated thanks to @dgzwiro !