Leetcode 49. 字母异位词分组

map set 容器暴力做

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<multiset<char>, int> AA;
        vector<vector<string>> ans;
        for (auto &x : strs) {
            multiset<char> A;
            for (auto &y : x)
                A.insert(y);
            if (AA.count(A))
                ans[AA[A]].push_back(x);
            else
                ans.push_back(vector<string>({ x })), AA[A] = ans.size() - 1;
        }
        return ans;
    }
};

类似优化

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<string, int> AA;
        vector<vector<string>> ans;
        for (auto &xx : strs) {
            string x = xx;
            sort(x.begin(), x.end());
            if (AA.count(x))
                ans[AA[x]].push_back(xx);
            else
                ans.push_back(vector<string>({ xx })), AA[x] = ans.size() - 1;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/80163153