Skip to content

Instantly share code, notes, and snippets.

@anupsavvy
Created July 29, 2011 04:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anupsavvy/1113100 to your computer and use it in GitHub Desktop.
Save anupsavvy/1113100 to your computer and use it in GitHub Desktop.
Write a method to sort an array of strings so that all the anagrams are next to each other.
public class Puzzle{
public Puzzle(){
//TODO
}
public static String[] sortStrings(String[] arr){
if(arr == null || arr.length == 0 || arr.length == 1)
return arr;
class StringComparator implements Comparator<String>{
private String sort(String s){
char[] letters = s.toCharArray();
Arrays.sort(letters);
return new String(letters);
}
public int compare(String s1, String s2){
return sort(s1).compareTo(sort(s2));
}
}
Arrays.sort(arr,new StringComparator());
return arr;
}
}
class PuzzleException extends RuntimeException{
public PuzzleException(String message){
super(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment