LeetCode49. 字母异位词分组

题目:给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

题目分析:用一个map的键来保存一个字母类型,值表示相同类型的字母组合。然后我们保留所有的“键值对”中的值就可以了。

代码展示:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<string,vector<string>> mp;
        vector<vector<string>> res;
        for(int i=0;i<strs.size();i++){
            string temp = strs[i];
            sort(temp.begin(),temp.end());
            mp[temp].push_back(strs[i]);
        }
        for(map<string,vector<string>>::iterator it=mp.begin();it!=mp.end();it++){
            res.push_back(it->second);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/jaster_wisdom/article/details/81118875