diff --git a/leetcode/src/main/java/com/wyl/leetcode/GroupAnagrams.java b/leetcode/src/main/java/com/wyl/leetcode/GroupAnagrams.java new file mode 100644 index 0000000..5209162 --- /dev/null +++ b/leetcode/src/main/java/com/wyl/leetcode/GroupAnagrams.java @@ -0,0 +1,48 @@ +package com.wyl.leetcode; + +import java.util.*; + +/** + * 49.给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 + *

+ * 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。 + *

+ * 示例 1: + *

+ * 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] + * 输出: [["bat"],["nat","tan"],["ate","eat","tea"]] + * 示例 2: + *

+ * 输入: strs = [""] + * 输出: [[""]] + * 示例 3: + *

+ * 输入: strs = ["a"] + * 输出: [["a"]] + */ +public class GroupAnagrams { + /** + * 单词字母排序后的单词都是一样的 + */ + static public List> groupAnagrams(String[] strs) { + Map> 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"})); + } +}