题目大意

异位词,相同字母个数相同。

解题思路

法一:排序
法二:字符串hash
如果是hash成acc a1c2这种,因为同样要保证abc..字母顺序,所以

  • map,
  • 数组,每次都要遍历26次

    Code

    ```cpp vector> groupAnagrams(vector& strs) { vector > ans; unordered_map > mp; for (auto& it : strs) {
    1. std::string key = it;
    2. sort(key.begin(), key.end());
    3. mp[key].push_back(it);
    } for (auto& it : mp) {
      ans.push_back(it.second);
    
    } return ans; }

vector> groupAnagrams(vector& strs) { vector > ans; map > mp; for (auto it : strs) { std::string tmp = it; sort(tmp.begin(), tmp.end()); mp[tmp].push_back(it); } int cnt = 0; for (auto it : mp) { ans.push_back(it.second); } return ans; } // ps: 遍历map时迭代器是it->second,for-each时是it.second

```cpp
std::string get_num(int a) {
        std::string ans = "";
        while (a) {
            ans += a%10 + '0';
            a /= 10;
        }
        std::reverse(ans.begin(), ans.end());
        return ans;
    }
    std::string hash(std::string& str) {
        vector<int> v(26);
        for (auto& it : str) {
            v[it-'a'] ++;
        }
        string res = "";
        for (int i=0; i<26; i++) {
            if (v[i] == 0) continue;
            res += (char)(i+'a') + get_num(v[i]);
        }
        return res;
    }

    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string> > ans;
        unordered_map<std::string,vector<string> > mp;
        for (auto& it : strs) {
            std::string key = hash(it);
            //std::cout << "key:" << key << std::endl;
            mp[key].push_back(it);
        }
        for (auto& it : mp) {
            ans.push_back(it.second);
        }
        return ans;
    }