49.字母异位词分组
链接:49.字母异位词分组
难度:Medium
标签:数组、哈希表、字符串、排序
简介:给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
题解 1 - typescript
- 编辑时间:2020-12-14
- 执行用时:176ms
- 内存消耗:50.8MB
- 编程语言:typescript
- 解法介绍:利用 map 去储存,key 重新变换。
function groupAnagrams(strs: string[]): string[][] {
  const cache: Record<string, string[]> = {};
  const toKey = (str: string) =>
    str
      .split('')
      .sort((a, b) => a.codePointAt(0)! - b.codePointAt(0)!)
      .join('');
  for (const str of strs) {
    const key = toKey(str);
    let arr = cache[key];
    if (!arr) {
      cache[key] = arr = [];
    }
    arr.push(str);
  }
  return Object.values(cache);
}
题解 2 - cpp
- 编辑时间:2021-12-23
- 执行用时:24ms
- 内存消耗:19MB
- 编程语言:cpp
- 解法介绍:对字符串进行排序后归并。
class Solution {
   public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> m;
        for (int i = 0; i < strs.size(); i++) {
            string str = strs[i];
            string head = str;
            sort(head.begin(), head.end());
            m[head].push_back(str);
        }
        vector<vector<string>> ans;
        for (auto it = m.begin(); it != m.end(); it++) {
            ans.push_back(it->second);
        }
        return ans;
    }
};