leetcode 随笔 Group Anagrams --hash的使用

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

输入为多个字符串,对字符串进行分类

自己写的代码超时了,跑不过最后一个样例。

看了一下discuss,发现还是写的太复杂,虽然也用到了hash,字符串的比较是一个字符一个字符比,就很蠢。

这里贴一个discuss里的优秀答案把

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
	unordered_map<string, vector<string>> count;
	int i = 0;
	for (auto s : strs)
	{
		sort(s.begin(), s.end());
		count[s].push_back(strs[i++]);
	}
	vector<vector<string>> res;
	for (auto n : count){
		res.push_back(n.second);
	}
	return res;
}
};

猜你喜欢

转载自blog.csdn.net/Runner_of_nku/article/details/79972914