力扣 面试题 10.02. 变位词组

题目说明

  • 编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。

    注意:本题相对原题稍作修改

  • 说明:

    • 所有输入均为小写字母。
    • 不考虑答案输出的顺序。

示例

示例1:

1
2
3
4
5
6
7
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

笔者理解

此题是一道哈希表算法问题,在力扣题库中被定义为中等题。

解法

当笔者阅读完此题后,发现此题采用哈希表进行记录比较容易求解,让我们来看看具体如何实现的吧。

实现

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
class Solution {
/*
* 哈希表
* 排序
*/
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();

for (int i = 0; i < strs.length; i++) {
// 将字符串转化为字节数组进行排序
char[] ch = strs[i].toCharArray();
Arrays.sort(ch);
String s = new String(ch);
List<String> temp;
// 排序之后对当前字符串进行HashMap记录
if (map.getOrDefault(s, null) == null) {
temp = new ArrayList<>();
}
else {
temp = map.get(s);
}
temp.add(strs[i]);
map.put(s, temp);
}

List<List<String>> result = new ArrayList<>();
// 取出所有变位词的记录
for(List<String> list : map.values()) {
result.add(list);
}

return result;
}
}

时间空间效率都还行,可见此解法还比较适合此题;

image.png

总结

本题是今天的每日一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。