[Leetcode]49. Group Anagrams

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.
题意:如果一个字符串只是字母的顺序不同,那么就归为一类,按类输出
思路:先对每个单词的字母排序,然后用map存每个排序之后的字符串和原来的字符串的对应关系,然后按照映射关系输出

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string,vector<string>>hash;
        for(auto s:strs)
        {
            string temp=s;
            sort(temp.begin(),temp.end());
            hash[temp].push_back(s);
        }
        int len=hash.size();
         vector<vector<string> >ans(len);
        int index=0;
        for(auto i:hash)
        {
            ans[index++]=i.second;
        }
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容