Leetcode 49. Group Anagrams (Medium) (cpp)

Leetcode 49. Group Anagrams (Medium) (cpp)

Tag: Hash Table, String

Difficulty: Medium


/*

49. Group Anagrams (Medium)

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note: All inputs will be in lower-case.

*/
class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        vector> res;
        vector primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107};
        unordered_map mapping;
        int pos = 0;
        for (auto s : strs) {
            long temp = 1;
            if (s != "") {
                for (auto cha : s) {
                    temp *= primes[cha - 'a'];
                }
            } else {
                temp = 107;
            }
            if (mapping.find(temp) == mapping.end()) {
                mapping[temp] = pos++;
                res.push_back(vector{s});
            } else {
                res[mapping[temp]].push_back(s);
            }
        }
        return res;
    }
};

Leetcode 49. Group Anagrams (Medium) (cpp)_第1张图片

你可能感兴趣的:(Leetcode,C++,C++,Leetcode,Hash,Table,Leetcode,String)