leetcode-49-字母异位词分类

//思路差不多,有比较简洁的写法(第二种)

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        int N = strs.size(), index=0;
        vector<vector<string>> res;
        vector<string> temp;
        map<string, int> dict;
        string sorted_str;
        for (int i = 0; i < N; i++) {
            sorted_str = strs[i];
            sort(sorted_str.begin(), sorted_str.end());
            if (dict.find(sorted_str) == dict.end()) {
                dict.insert(make_pair(sorted_str, index++));
                temp.push_back(strs[i]);
                res.push_back(temp);
                temp.clear();
            }
            else {
                res[dict[sorted_str]].push_back(strs[i]);
            }
        }
        return res;
    }
};

int main()
{        
    Solution sol;
    vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
    vector<vector<string>> res = sol.groupAnagrams(strs);
    for (int i = 0; i < res.size(); i++) {
        for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << ",";
        cout << endl;
    }
    cout<< endl;
    return 0;
}

//以下是简洁写法

(找不着了,大概是建立顺序字符串到同构字符串的dict,最后循环存储所有value,这样就不需要一个一个存,直接存的就是vector)

 

相关文章:

  • 2021-08-25
  • 2021-11-15
  • 2021-09-01
  • 2021-09-15
  • 2021-07-31
  • 2021-06-04
  • 2021-08-10
  • 2021-05-18
猜你喜欢
  • 2022-02-06
  • 2021-05-27
  • 2021-12-27
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
  • 2021-04-09
相关资源
相似解决方案