首页 > 代码库 > CC150 - 11.2
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 @Override50 public int compare(String o1, String o2) {51 // TODO Auto-generated method stub52 return sortChars(o1).compareTo(sortChars(o2));53 }54 }
注意:comparator的重写方法!!!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。