leetcode 49. 字母异位词分组

This commit is contained in:
wyl
2024-06-25 16:40:22 +08:00
parent 78247204fd
commit 2101e9562b
@@ -0,0 +1,48 @@
package com.wyl.leetcode;
import java.util.*;
/**
* 49.给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
* <p>
* 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
* <p>
* 示例 1:
* <p>
* 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
* 输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
* 示例 2:
* <p>
* 输入: strs = [""]
* 输出: [[""]]
* 示例 3:
* <p>
* 输入: strs = ["a"]
* 输出: [["a"]]
*/
public class GroupAnagrams {
/**
* 单词字母排序后的单词都是一样的
*/
static public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
byte[] res = strs[i].getBytes();
Arrays.sort(res);
String s = new String(res);
if (map.containsKey(s)) {
map.get(s).add(strs[i]);
} else {
int finalI = i;
map.put(s, new ArrayList<>() {{
add(strs[finalI]);
}});
}
}
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
System.out.println(groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
}
}