My Solution In C++ With HashMap


  • 0
    L
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string> > result;
            if (strs.empty())
                return result;
            // 把原数组拷贝一份,因为要排序
            vector<string> str(strs);
            map<string, vector<int> > mp;
            // 完成分组
            for (unsigned int i = 0; i < str.size(); i++) {
                sort(str[i].begin(), str[i].end());
                mp[str[i]].push_back(i);
            }
            // 按顺序添加至结果容器
            for (auto it = mp.begin(); it != mp.end(); ++it) {
                // it->second是一个vector,记录出现的下标
                vector<string> temp;
                for (unsigned int i = 0; i < it->second.size(); i++) {
                    temp.push_back(strs[it->second[i]]);
                }
                sort(temp.begin(), temp.end());
                result.push_back(temp);
            }
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.