【C++】【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”]
]

思路

string也可以排序,通过sort方法,得到每个string从小到大的排序string,如果是同一类的string,排序后可得到相同的字符串,因此可以作为map的key使用。

代码

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<string, vector<string>> dic;
        for (int i = 0; i< strs.size(); i++) {

            string s1 = strs[i];
            sort(s1.begin(), s1.end());
            if (dic.find(s1) != dic.end()) {
                dic[s1].push_back(strs[i]);
            } else {
                vector<string> result = {strs[i]};
                dic[s1] = result;
            }
        }
        vector<vector<string>> result;
        for (map<string, vector<string>>::iterator i = dic.begin(); i != dic.end(); i++) {
            result.push_back(i->second);
        }
        return result;
    }
};

你可能感兴趣的:(LeetCode)