Question:
Write a method to sort an array of strings so that all the anagrams are next to each other.
1 package POJ; 2 3 import java.util.Arrays; 4 import java.util.Comparator; 5 import java.util.Hashtable; 6 import java.util.LinkedList; 7 import java.util.List; 8 9 public class Main { 10 11 /** 12 * 13 * 11.2 Write a method to sort an array of strings so that all the anagrams are next to each other. 14 * 15 */ 16 public static void main(String[] args) { 17 Main so = new Main(); 18 } 19 20 public void sort(String[] list) { 21 Hashtable<String, LinkedList<String>> ht = new Hashtable<String, LinkedList<String>>(); 22 AnagramCompare ac = new AnagramCompare(); 23 for (String s : list) { 24 String key = ac.sortChars(s); 25 if (!ht.contains(key)) { 26 ht.put(key, new LinkedList<String>()); 27 } 28 LinkedList<String> anagrams = ht.get(key); 29 anagrams.add(s); 30 } 31 int index = 0; 32 for (String s : ht.keySet()) { 33 LinkedList<String> tempList = ht.get(s); 34 for (String t : tempList) { 35 list[index] = t; 36 index++; 37 } 38 } 39 } 40 } 41 42 class AnagramCompare implements Comparator<String> { 43 public String sortChars(String s1) { 44 char[] temp = s1.toCharArray(); 45 Arrays.sort(temp); 46 return new String(temp); 47 } 48 49 @Override 50 public int compare(String o1, String o2) { 51 // TODO Auto-generated method stub 52 return sortChars(o1).compareTo(sortChars(o2)); 53 } 54 }
注意:comparator的重写方法!!!