Leetcode49.Group_Anagrams

用一个整数数组记录每个字母出现次数,再把数组内的信息转换为string作为散列表的key。
转换方法:用一个字符分隔,录入每个字母出现次数。
for (int i = 0; i < 26; i++) { alphabet.push_back('a' + i); alphabet.push_back(record[i]); }
时间复杂:O(N*K)(K位字符串最大长度)
C++代码:

class Solution {
public:
	vector<vector<string>> result;
	vector<vector<string>> groupAnagrams(vector<string>& strs) {
		if (strs.empty())
			return {};
		if (strs.size() == 1)
			return { strs };
		unordered_map<string, vector<string>> hash;
		vector<string> key;
		for (auto x : strs)
		{
			int record[26] = { 0 };
			string alphabet;
			for (auto ch : x)
			{
				record[ch - 'a']++;
			}
			for (int i = 0; i < 26; i++)
			{
				alphabet.push_back('a' + i);
				alphabet.push_back(record[i]);
			}
			if (hash.find(alphabet) != hash.end())
			{
				hash[alphabet].push_back(x);
			}
			else
			{
				key.push_back(alphabet);
				vector<string>* unfound = new vector<string>;
				unfound->push_back(x);
				hash.insert(make_pair(alphabet, *unfound));
			}
		}
		for (auto x : key)
		{
			result.push_back(hash[x]);
		}
		return result;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82776817