Leetcode 49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

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

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

题目链接:https://leetcode.com/problems/group-anagrams/

思路:这题复杂度有待降低,cmp函数中先把每个string按字典序整好,然后对strs排序,然后分组的时候,再排序比较

class Solution {
public:
      static  bool comp(string s1,string s2)
    {
          sort(s1.begin(),s1.end());
          sort(s2.begin(),s2.end());
              return s1> groupAnagrams(vector& strs) {
        vector> res;
        vector tmp;
        int len=strs.size();
        if(len==0)
            return res;
        if(len==1)
        {
            tmp.push_back(strs[0]);
            res.push_back(tmp);
            tmp.clear();
            return res;
        }
        sort(strs.begin(),strs.end(),comp);
        for(int i=0;i

可以使用map来,和我的思路一样,但是人家使用的工具很好哦,学习到了

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

复杂度降低了很多。虽然仅供参考,但这个确实好了很多

参考链接:https://leetcode.com/problems/group-anagrams/discuss/19224/A-clean-c%2B%2B-solution-with-unordered_map

你可能感兴趣的:(Leetcode)