[LeetCode] 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.

 

给定一个字符串数组,对其中相同元素组成的字符串进行分类

思路:

1. 因为是对相同元素构成的字符串进行分类,可以先将构造一个新数组,数组元素是给定字符串数组每个字符串的排序。

2. 通过新数组,结合multimap(元素值,在数组中的索引值)来定位新数组相同(原数组相似)的元素位置。

3. 遍历这个map将相似的元素放入结果数组中即可。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        if (strs.empty())
            return res;
        int n = strs.size();
        vector<string> rstrs;
        for (string str : strs)
        {
            sort(str.begin(), str.end());
            rstrs.push_back(str);
        }
        multimap<string, int> mmap;
        unordered_set<string> s;
        for (int i = 0; i < n; ++i)
        {
            mmap.insert({rstrs[i], i});
        }
        vector<string> tmp;
        s.insert(mmap.begin()->first);
        for (auto it = mmap.begin(); it != mmap.end(); ++it)
        {
            if (s.find(it->first) != s.end())
            {
                tmp.push_back(strs[it->second]);
            }
            else
            {
                res.push_back(tmp);
                tmp.clear();
                s.insert(it->first);
                tmp.push_back(strs[it->second]);
            }
        }
        res.push_back(tmp);
        return res;
        
    }
};

 LeetCode Discuss

优化代码,思路类似:

1. 排序

2. 将相同的字符串直接放入数组中

3. 将每个数组放到结果数组返回

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> mp;
        for (auto str : strs)
        {
            string tmp = str;
            sort(tmp.begin(), tmp.end());
            mp[tmp].push_back(str);
        }
        vector<vector<string>> res;
        for (auto m : mp)
        {
            vector<string> svec(m.second.begin(), m.second.end());
            res.push_back(svec);
        }
        return res;
    }
};

 

posted @ 2018-08-06 13:45  immjc  阅读(108)  评论(0编辑  收藏  举报