Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

Summary: To sort and compare strings, using map to record distinct strings.

 1 class Solution {
 2 public:
 3     vector<string> anagrams(vector<string> &strs) {
 4         vector<string> result;
 5         map<string, int> str_map;
 6         for(int i = 0; i < strs.size(); i ++) {
 7             string tmp = strs[i];
 8             std::sort(tmp.begin(), tmp.end());
 9             if(str_map.find(tmp) == str_map.end()) {
10                 str_map[tmp] = i;
11             }else {
12                 result.push_back(strs[i]);
13                 if(str_map[tmp] >= 0 ) {
14                     result.push_back(strs[str_map[tmp]]);
15                     str_map[tmp] = -1;
16                 }
17             }
18         }
19         return result;
20     }
21 };

 

相关文章:

  • 2022-01-10
  • 2022-12-23
  • 2021-12-20
  • 2021-09-22
  • 2021-05-18
  • 2021-07-01
  • 2021-09-30
猜你喜欢
  • 2021-08-10
  • 2022-02-15
  • 2022-01-18
  • 2022-01-31
  • 2021-08-12
  • 2021-11-24
  • 2021-09-17
相关资源
相似解决方案