group-anagrams-lcci [计数统计]
codeflysafe Lv5

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

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

示例:

1
2
3
4
5
6
7
8
9

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

说明:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

由于只有小写字母,只需要申请一个长度为26的数组统计每一个字符串的字母数量即可(类似于hashcode的构造思想)。
这样所有的变位词可以映射到相同的数组,使用map,将数组(或者转为字符串)作为key,value 即是对应的字符数组。

Code

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
class Solution {
public:

string hashcode(vector<int> chs){
string ans = "";
for(int ch: chs){
ans.append(to_string(ch) + "_");
}
return ans;
}

vector<vector<string>> groupAnagrams(vector<string>& strs) {

// hash 编码
// eat tea tan ate nat bat
unordered_map<string,vector<string>> containers;
for(string str: strs){
vector<int> counts(26,0);
for(char c: str){
counts[c-'a'] ++;
}
containers[hashcode(counts)].emplace_back(str);
}
vector<vector<string>> res;
for(auto &p: containers){
res.push_back(p.second);
}
return res;

}
};
  • 本文标题:group-anagrams-lcci [计数统计]
  • 本文作者:codeflysafe
  • 创建时间:2021-07-18 09:13:16
  • 本文链接:https://codeflysafe.github.io/2021/07/18/group-anagrams-lcci/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论