Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:49. 字母异位词分组,数组计数+哈希表,JavaScript,详细注释 #181

Open
chencl1986 opened this issue Oct 5, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/group-anagrams/

解题思路:

如果你对这题不熟悉,可以先做242. 有效的字母异位词,以及我的题解LeetCode题解:242. 有效的字母异位词,数组计数,JavaScript,详细注释

  1. 使用Map保存最终结果,Map中存储的是分组后的异位词数组。
  2. 使用长度为26的数组对每个字母计数,index值由char.codePointAt(0) - 'a'.codePointAt(0)计算而来。
  3. 将计数后的数组转换成字符串,作为Map的key,存储相应的异位词字符串。
  4. 最后将Map转换为数组形式输出结果即可。
/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
  let resultMap = new Map(); // 使用Map保存结果

  for (const str of strs) {
    let keyArr = new Array(26).fill(0); // 使用数组统计所有字母的个数

    for (const char of str) {
      // 计算字母与a的码点差值,其差值会在0-25
      const index = char.codePointAt(0) - 'a'.codePointAt(0);
      // 每个字母的相应数量+1
      keyArr[index]++;
    }

    // 将数组转换成字符串,用于保存相应异位词的结果
    const key = JSON.stringify(keyArr);

    // 将异位词按照对应的key存储到Map中
    resultMap.get(key)
      ? resultMap.get(key).push(str)
      : resultMap.set(key, [str]);
  }

  // 将Map转换为数组并输出结果
  return [...resultMap.values()];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant