美文网首页
[Leetcode]49. Group Anagrams

[Leetcode]49. Group Anagrams

作者: 木易yr | 来源:发表于2019-08-20 00:22 被阅读0次

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;
    }
};

相关文章

网友评论

      本文标题:[Leetcode]49. Group Anagrams

      本文链接:https://www.haomeiwen.com/subject/qcwysctx.html