Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created February 24, 2013 03:31
Show Gist options
  • Save charlespunk/5022454 to your computer and use it in GitHub Desktop.
Save charlespunk/5022454 to your computer and use it in GitHub Desktop.
Write a methos to sort an array of strings so that all the anagrams are next to each other.
public String[] sortAnagrams(String[] input){
HashMap<String, ArrayList<String>> map = new HashMap<>();
ArrayList<String> output = new ArrayList<>();
for(String word : input){
String key = sort(word);
if(map.contasinsKey(key)) map.get(key).add(word);
else map.put(key, new ArrayList<String>(Arrays.asList(key)));
}
for(String key : map.keySet()){
output.addAll(map.get(key));
}
return (String[]) output.toArray(new String[0]);
}
public static String sortWord(String word){
char[] cs = word.toCharArray();
Arrays.sort(cs);
return String.valueOf(cs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment