剑指offer033-变位词组
题目
给定一个字符串数组 strs ,将 变位词 组合在一起。 可以按任意顺序返回结果列表。
注意:若两个字符串中每个字符出现的次数都相同,则称它们互为变位词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
注意:本题与主站 49 题相同: https://leetcode-cn.com/problems/group-anagrams/
👍 11👎 0
思路
先排序,分桶收集
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class Solution { public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>(); if (strs.length == 0) { List<String> a = Arrays.asList(""); res.add(a); return res; }
if (strs.length == 1) { List<String> a = Arrays.asList(strs); res.add(a); return res; }
Map<String, List<String>> map = new HashMap<>(); for (int i = 0; i < strs.length; i++) { String str = strs[i]; String key; if (str == "") { key = ""; } else { char[] chars = str.toCharArray(); Arrays.sort(chars); key = Arrays.toString(chars); } if (map.containsKey(key)) { map.get(key).add(strs[i]); } else { List<String> s = new ArrayList<>(); s.add(strs[i]); map.put(key, s); } }
for (String key : map.keySet()) { List<String> t = map.get(key); res.add(t); } return res; } }
|