Skip to content

Instantly share code, notes, and snippets.

@Bekt
Created December 25, 2012 00:58
Show Gist options
  • Save Bekt/4371211 to your computer and use it in GitHub Desktop.
Save Bekt/4371211 to your computer and use it in GitHub Desktop.
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