Created
December 25, 2012 00:58
-
-
Save Bekt/4371211 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String[] sortByAnagrams(String[] words) { | |
Map<String, List<Integer>> map = new TreeMap<String, List<Integer>>(); | |
String[] resultArray = new String[words.length]; | |
//Map sorted words to indecies | |
for(int i=0; i<words.length; i++) { | |
char[] ch = words[i].toLowerCase().toCharArray(); | |
Arrays.sort(ch); | |
String s = String.valueOf(ch); | |
List<Integer> list = map.get(s); | |
if(list == null) { | |
list = new ArrayList<Integer>(); | |
map.put(s, list); | |
} | |
list.add(i); | |
} | |
//Put into result array in sorted order | |
Set<String> keySet = map.keySet(); | |
int index = 0; | |
for(String s : keySet) { | |
List<Integer> list = map.get(s); | |
for(Integer i : list) | |
resultArray[index++] = words[i]; | |
} | |
return resultArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment