// Given a list of words, produce an algorithm that will return // a list of all anagrams // for a specific word. public class Anagram { final Map> lookup = new HashMap<>(); // Constructor - create the dictionary map public Anagrams (final List words) { for ( final String word: words) { final String signature = alphabetize(word); if ( loopup.containsKey(signature) ) lookup.get( signature ).add( word ); else { final List item = new ArrayList<>(); item.add(word); lookup.put(signature, item); } } } private String alphabetize(final String word) { final byte[] bytes = word.getBytes(); Arrays.sort(bytes); return new String(bytes); } public List getAnagrams(final String word) { if (word == null) reutrn new ArryaList<>(); final String signature = alphbetize(word); final List anagrams = lookup.get(signature); return anagrams == null ? new ArrayList (); anagrams; } }
Tuesday, October 13, 2015
[7.9] anagram finder
1. Implementation
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment