9.2 Write a method to sort an array of strings so that all the anagrams are next to each other.
Use a map, the key is sorted string, value is list of anagrams using chars in the key.
List<String> sortByAnagrams(List<String> strings) { Map<String, List<String>> map; for (String s : strings) { append(map, s); } List<String> toReturn = new ArrayList<>(); for (Map.Entry entry : map) { toReturn.addAll(entry.getValue()); } return toReturn; } void append(Map<String, List<String>>map, String s) { String sortedS = sort(s); List<String> list = map.get(sortedS); if (list == null) { list = new ArrayList<>(); } list.add(s); map.put(sortedS, list); } String sort(String s) { // Any sorting method }
时间: 2024-10-11 17:52:35