Java经典面试题将一个字符串数组进行分组输出,每组中的字符串都由相同的字符组成
题目:
将一个字符串数组进行分组输出,每组中的字符串都由相同的字符组成
举个例子:输入[“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
输出[[“ate”,“eat”,“tea”],[“nat”,“tan”],[“bat”]]
public class CommonDigitFinder {public static void main(String[] args) {String[] strs = {"ate", "tae", "tan", "ant", "eat","bat"};System.out.println(grouper(strs));}public static List<List<String>> grouper(String[] strs) {if (strs == null || strs.length == 0) {return new ArrayList<>();}Arrays.sort(strs);Map<String, List<String>> map = new HashMap<>();for (String str : strs) {char[] c = str.toCharArray();Arrays.sort(c);String sortedStr = String.valueOf(c);if (!map.containsKey(sortedStr)) {map.put(sortedStr, new ArrayList<>());}map.get(sortedStr).add(str);}return new ArrayList<>(map.values());}
}