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

49. Group Anagrams #108

Open
Tcdian opened this issue Apr 12, 2020 · 1 comment
Open

49. Group Anagrams #108

Tcdian opened this issue Apr 12, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 12, 2020

49. Group Anagrams

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

Example

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note

  • 所有输入均为小写字母
  • 不考虑答案输出的顺序
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 12, 2020

Solution

  • JavaScript Solution
/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) {
    const hashMap = new Map();
    for (let i = 0; i < strs.length; i++) {
        const letters = new Array(26).fill(0);
        for (let k = 0; k <strs[i].length; k++) {
            letters[strs[i].charCodeAt(k) - 97] += 1;
        }
        const lettersMark = letters.join();
        if (!hashMap.has(lettersMark)) {
            hashMap.set(lettersMark, []);
        }
        hashMap.set(lettersMark, [...hashMap.get(lettersMark), strs[i]]);
    }
    return [...hashMap.values()];
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant