王廷瑋|數位醫療|智慧醫療: 49. Group Anagrams WFU

2024年7月4日 星期四

49. Group Anagrams

49. Group Anagrams


給定一個字符串數組 strs,將異位詞分組在一起。你可以以任意順序返回答案。

異位詞是一個詞或短語,由不同單詞或短語的字母重新排列組成,通常使用所有原始字母且只使用一次。

範例 1:

輸入:strs = ["eat","tea","tan","ate","nat","bat"] 輸出:[["bat"],["nat","tan"],["ate","eat","tea"]]


Python


from typing import List
from collections import defaultdict

class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_map = defaultdict(list)
for s in strs:
# Sort the string to create a unique key for each group of anagrams
key = ''.join(sorted(s))
anagram_map[key].append(s)
# Return the values of the dictionary as a list of lists
return list(anagram_map.values())

19.64MB, 85ms


C++


#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> anagram_map;
// Iterate through each string in the input list
for (const string& s : strs) {
string key = s;
sort(key.begin(), key.end()); // Sort the string to create a key
anagram_map[key].push_back(s); // Add the original string to the map
}
// Prepare the result vector
vector<vector<string>> result;
for (auto& pair : anagram_map) {
result.push_back(pair.second); // Add each group of anagrams to the result
}
return result;
}
};

23.65MB, 29ms


Javascript


/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
const anagramMap = new Map();

for (const str of strs) {
// Sort the string to create a unique key for each group of anagrams
const key = str.split('').sort().join('');
// If the key is not already in the map, add it with an empty array
if (!anagramMap.has(key)) {
anagramMap.set(key, []);
}

// Append the original string to the array for this key
anagramMap.get(key).push(str);
}

// Convert the values of the map to an array of arrays and return it
return Array.from(anagramMap.values());
};

// Example usage:
const strs = ["eat", "tea", "tan", "ate", "nat", "bat"];
console.log(groupAnagrams(strs));

62.4MB, 97ms