LeetCode | 49. Group Anagrams 哈希表

本文介绍了一种使用哈希表快速解决字母异位词分组问题的方法,通过将字符串排序后作为键,原字符串作为值存储,实现了高效查找与分组。此外,还提供了一个备选方案,利用字符计数来实现相同目标。

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

Givenan array of strings, group anagrams together.

Forexample, given: ["eat", "tea", "tan","ate", "nat", "bat"], 
Return:

[

  ["ate","eat","tea"],

 ["nat","tan"],

  ["bat"]

]

这题记住很重要的几点能够非常快的解题,

首先unordered_map是哈希表,查询速度为O(1),其实map的key可以为string,也可以为其他值,这题很明显是查找所有拥有相同stringkey的string集合,所以可以将数组中每一个排序之后的string作为key,将其所对应的string集合作为value,直接使用哈希表能够非常快的得到结果

以后在做在数组中统计所有相同的值的个数或者是要求输出所有相同的值的时候可以直接使用unordered_map解决!

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
	unordered_map<string, vector<string>> theStore;
	string tmp;
	for (int i = 0; i < strs.size(); i++)
	{
		tmp = strs[i];
		sort(tmp.begin(), tmp.end());
		theStore[tmp].push_back(strs[i]);
	}
	vector<vector<string>> result;
	for (auto it = theStore.begin(); it != theStore.end(); it++)
	{
		result.push_back(it->second);
	}
	return result;
}
};


这题做的我心累,首先需要注意的是当在循环里面重复声明数组的时候,实际上数组指针会重用,如果你不使用类似于={0}的方法来初始化的话,重新声明的数组会使用上一个声明的数组指针,这个时候假如你将数组指针赋值给了其他的部分,那么这个时候会出错,所以这个时候要记得使用指针=new int()的方式来声明!

以后要记住,尽量少用memset(sizeof(p)),这里的p是指针,这种方法在某种情况下是错误的!

class Solution {
public:
int checkInCharsStore(vector<int *> &theCharsStore, int * p)
{
	for (int i = 0; i < theCharsStore.size(); i++)
	{
		int j = 0;
		for (j = 0; j < 26; j++)
		{
			if (theCharsStore[i][j] != p[j])
				break;
		}
		if (j == 26)
		{
			return i;
		}
	}
	return -1;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
	vector<int *> theCharsStore;
	vector<vector<string>> result;
	vector<string> tmp;
	for (int i = 0; i < strs.size(); i++)
	{
		int  * p=new int[26];
		memset(p, 0, sizeof(int)*26);

		for (auto u : strs[i])
			p[u - 'a']++;
		int l = checkInCharsStore(theCharsStore, p);
		if (l == -1)
		{
			tmp.clear(); tmp.push_back(strs[i]);
			result.push_back(tmp);
			theCharsStore.push_back(p);
		}
		else
		{
			result[l].push_back(strs[i]);
		}
	}
	return result;
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值