标签:interview
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 }
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1586151