文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 49. Group Anagrams

2. Solution

  • Version 1
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        unordered_map<string, vector<string>> m;
        for(string s : strs) {
            string temp = s;
            sort(temp.begin(), temp.end());
            if(m.find(temp) != m.end()) {
                m[temp].push_back(s);
            }
            else {
                vector<string> anagrams;
                anagrams.push_back(s);
                m[temp] = anagrams;
            }
        }
        for(auto iter: m) {
            result.push_back(iter.second);
        }
        return result;
    }
};
  • Version 2
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        unordered_map<string, vector<string>> m;
        for(string s : strs) {
            string temp = s;
            sort(temp.begin(), temp.end());
            m[temp].push_back(s);
        }
        for(auto iter: m) {
            result.push_back(iter.second);
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/group-anagrams/description/

相关文章:

  • 2022-02-25
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2021-11-20
  • 2022-12-23
猜你喜欢
  • 2021-07-08
  • 2021-07-26
  • 2022-03-09
  • 2021-08-10
  • 2021-12-16
  • 2022-02-04
  • 2021-10-29
相关资源
相似解决方案