題目:
????????給你一個字符串數組,請你將?字母異位詞?組合在一起。可以按任意順序返回結果列表。字母異位詞?是由重新排列源單詞的所有字母得到的一個新單詞。
示例 1:
- 輸入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
- 輸出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
- 輸入: strs = [""]
- 輸出: [[""]]
示例 3:
- 輸入: strs = ["a"]
- 輸出: [["a"]]? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
解答:
思路1:
- ?將數組中元素轉換成字符數組,然后對字符數組排序
- ?將排序后的字符數組轉換成String,存入Map中,key:排序的字符數組,value:原數組中元素
- ?遍歷Map,返回結果
private static List<List<String>> method1(String[] strs) {List<List<String>> result = new ArrayList<>();Map<String, List<String>> map = new HashMap<>(8);for (int i = 0; i < strs.length; i++) {char[] chars = strs[i].toCharArray();Arrays.sort(chars);String key = new String(chars);if (map.containsKey(key)) {map.get(key).add(strs[i]);} else {List<String> list = new ArrayList<>();list.add(strs[i]);map.put(key, list);}}result.addAll(map.values());return result;}