LeetCode 49. Group Anagrams

Given an array of strings, group anagrams together.

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

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

运用一下STL数据结构就行了。

  • map记录一下在vector中的位置就行了。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        
        vector<vector<string>> ans;
        unordered_map<string, int> mp;
        
        int res = 0;
        for(int i=0; i<strs.size(); ++ i)
        {
            string str = strs[i];
            sort(str.begin(), str.end());
            if(mp.count(str) > 0)
                ans[mp[str]].push_back(strs[i]);
            else
            {
                ans.push_back(vector<string>{strs[i],});
                mp[str] = res ++;
            }
        }
        return ans;
    }
};

原文地址:https://www.cnblogs.com/aiterator/p/6653456.html