[LeetCode] Group Anagrams

本文介绍了一种使用 C++ 实现的高效算法来解决将字符串数组中的同字母异序词进行分组的问题。该算法利用了哈希表与多集合的数据结构,并通过排序或计数排序来提高字符串比较效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The function signature has been updated to return a more intuitive vector<vector<string>>which treats a single string as a group of anagrams consisting of only itself.

The idea is to use an unordered_map to store those strings that are anagrams. We use the sorted string as the key and the string itself as the value. The strings are stored in a multisetsince there may be duplicates. Moreover, multiset will sort them by default as we desire.

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         unordered_map<string, multiset<string>> mp;
 5         for (string s : strs) {
 6             string t = s; 
 7             sort(t.begin(), t.end());
 8             mp[t].insert(s);
 9         }
10         vector<vector<string>> anagrams;
11         for (auto m : mp) { 
12             vector<string> anagram(m.second.begin(), m.second.end());
13             anagrams.push_back(anagram);
14         }
15         return anagrams;
16     }
17 };

Update: general sort takes O(nlogn) time. In this problem, since the string only contains lower-case alphabets, we can write a sorting function using counting sort (O(n) time) to speed up the sorting process. I write a string sorting functionstrSort below and using it to sort the string achieves the overall running time 72ms for this problem while the above code takes 76ms.

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         unordered_map<string, multiset<string>> mp;
 5         for (string s : strs) {
 6             string t = strSort(s);
 7             mp[t].insert(s);
 8         }
 9         vector<vector<string>> anagrams;
10         for (auto m : mp) { 
11             vector<string> anagram(m.second.begin(), m.second.end());
12             anagrams.push_back(anagram);
13         }
14         return anagrams;
15     }
16 private:
17     string strSort(string& s) {
18         int count[26] = {0}, n = s.length();
19         for (int i = 0; i < n; i++)
20             count[s[i] - 'a']++;
21         int p = 0;
22         string t(n, 'a');
23         for (int j = 0; j < 26; j++)
24             for (int i = 0; i < count[j]; i++)
25                 t[p++] += j;
26         return t;
27     } 
28 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值