Posted By

jerryvig on 04/04/12


Tagged

list java anagram


Versions (?)

ListAnagrams


 / Published in: Java
 

anagrams list in java

  1. public void listAnagrams( String input ) {
  2. String[] words = input.split(" ");
  3. HashMap<String,ArrayList<String>> keyIndex = new HashMap();
  4.  
  5. for ( int i=0; i<words.length; i++ ) {
  6. String key = sort( words[i] );
  7. if ( keyIndex.get(key) == null ) {
  8. ArrayList<String> indices = new ArrayList();
  9. indices.put( words[i] );
  10. keyIndex.put( key, words[i] );
  11. }
  12. else {
  13. ArrayList<String> indices = keyIndex.get(key);
  14. indices.add( words[i] );
  15. }
  16. }
  17.  
  18. Set<String> keys = keyIndex.keySet();
  19. Iterator keyIter = keys.getIterator();
  20. while ( keyIter.hasNext() ) {
  21. String key = keyIter.next();
  22. ArrayList<String> keyWords = keyIndex.get( key );
  23. System.out.print( key + ": " );
  24. for ( String keyWord : keyWords ) {
  25. System.out.print( keyWord + " " );
  26. }
  27. System.out.print( "\n" );
  28. }
  29. }

Report this snippet  

You need to login to post a comment.