CC150 - 11.2

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的重写方法!!!

转载于:https://www.cnblogs.com/Phoebe815/p/3923666.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值