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

 

转载于:https://www.cnblogs.com/xiaomaoliu/p/4486630.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值