Sort Anagrams

cc150 Question 11.2 Sort array of string that anagrams next to each other. 

(leetcode 也有类似题目)

Solution 1: 借助Arrays.sort, 需要重写comparator。

 1     public static class AnagramComparator implements Comparator<String> {
 2         
 3         //***********need learn more about comparator***********************//
 4         /*
 5          * The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals 
 6          * if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.(non-Javadoc)
 7          * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
 8          */
 9         public int compare(String s1, String s2) {
10             return sortChars(s1).compareTo(sortChars(s2));//compareTo(String anotherString)
11             /*
12              *  The result <0  if this String object lexicographically precedes the argument string. 
13              *  The result>0  if this String object lexicographically follows the argument string. 
14              *  The result == 0 if the strings are equal; 
15              */
16         }
17         public String sortChars(String s) {
18             //lee  -> eel;  
19             char[] content = s.toCharArray();
20             Arrays.sort(content);//sort alph in order
21             return new String(content);
22         }
23     }
View Code

Solution 2: Hashtable

 hashtable 存储<key, List<String>anagrams>, 这里key可以简单的将string sort。

 1 public static void sortAnagrams(String[] array){
 2         Hashtable<String,LinkedList<String>> htable = new Hashtable<String, LinkedList<String>>();
 3         
 4         //store key in hashtable
 5         for(String s: array){
 6             String key = sortString(s);
 7             if(!htable.containsKey(key)) {
 8                 htable.put(key, new LinkedList<String>());
 9             }
10             //not else cause must add s to linkedlist
11             LinkedList<String> anagrams = htable.get(key);
12             anagrams.push(s);
13         }
14         // Convert hash table to array 
15         int index = 0;
16         
17         for (String key : htable.keySet()) {
18             LinkedList<String> list = htable.get(key);
19             
20             for (String t : list) {
21                 array[index] = t;
22                 index++;
23             }
24         }
25         
26         
27     }
View Code

 

posted @ 2015-05-08 04:20  xiaomaoliu  阅读(115)  评论(0编辑  收藏  举报