49. 字母异位词分组

  1. 题目链接

  2. 解题思路:

    • 方法一:每个「字母异位词」,排序后的结果,都是一致的,所以,可以用一个map,key就是排序后的字符串,value就是所有的「字母异位词」。

    • 方法二:直接使用map,不需要排序得出来,看下面的代码

      class Solution {
      public:
          struct MyCompare{
              bool operator()(const vector<int> &v1, const vector<int> &v2) const{
                  int n1 = v1.size();
                  int n2 = v2.size();
                  if (n1 != n2) {
                      return n1 < n2; // 一定要这样写  可以写成 n1 >n2 不能写true/false
                  }
                  for (int i = 0; i < n1; ++i) {
                      if (v1[i] != v2[i]) {
                          return v1[i] < v2[i];   // 一定要这样写  可以写成 v1[i] >v2[i] 不能写true/false
                      }
                  }
                  return false;    // 返回false,表示map认为这是一个key
              }
          };
          vector<vector<string>> groupAnagrams(vector<string>& strs) {
              map<vector<int>, vector<string>, MyCompare> sameWords;
              int n = strs.size();
              for (int i = 0; i < n; ++i) {
                  vector<int> tmp(26, 0);    // 26个字母
                  for (int j = 0; j < strs[i].size(); ++j) {
                      tmp[strs[i][j] - 'a']++; 
                  }
                  if (sameWords.count(tmp) == 0) {    // 没有相同的词
                      sameWords[tmp] = {strs[i]};
                  } else {    // 有了
                      sameWords[tmp].push_back(strs[i]);
                  }   
              }
              vector<vector<string>> ans;
              for (auto &it : sameWords) {
                  ans.push_back(it.second);
              }
              return ans;
          }
      };
      
posted @ 2024-12-20 16:53  ouyangxx  阅读(39)  评论(0)    收藏  举报