Friday, December 9, 2011

Write a method to sort an array of strings so that all the anagrams are next to each other.

The basic idea is to implement a normal sorting algorithm where you override the compareTo method to compare the “signature” of each string. In this case, the signature is the alphabetically sorted string.

1      public class AnagramComparator implements Comparator<String> {
2               public String sortChars(String s) {
3                       char[] content = s.toCharArray();
4                       Arrays.sort(content);
5                       return new String(content);
6               }
7         
8            public int compare(String s1, String s2) {
9                    return sortChars(s1).compareTo(sortChars(s2));
10           }
11     }
Now, just sort the arrays, using this compareTo method instead of the usual one.
12     Arrays.sort(array, new AnagramComparator());

No comments:

Post a Comment