【LeetCode 面试经典150题】49. Group Anagrams 字母异位词分组

49. Group Anagrams

题目大意

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

中文释义

给定一个字符串数组 strs,将变位词组合在一起。答案可以以任何顺序返回。

变位词是指通过重新排列不同单词或短语的字母而形成的单词或短语,通常使用所有原始字母恰好一次。

示例

Example 1:

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

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

限制条件

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] 由小写英文字母组成。

解题思路

方法

这个解决方案用于解决“Group Anagrams”问题,即将具有相同字母但排列不同的字符串分组。主要方法是使用哈希表来分组具有相同字符集的字符串。

  1. 创建哈希表

    • 使用 unordered_map<string, vector<string>>。键是排序后的字符串,值是原始字符串的数组。
  2. 遍历并分组

    • 遍历字符串数组 strs。对于每个字符串 s
      • 创建一个临时字符串 t,并将 s 的内容复制到 t
      • 对临时字符串 t 进行排序,使其字符按字典顺序排列。
      • 将原始字符串 s 添加到哈希表的相应键(即排序后的字符串 t)下的数组中。
  3. 提取结果

    • 遍历哈希表,将哈希表中的每个值(即每个分组的字符串数组)添加到最终结果 anagrams 中。

代码

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> map;
        for (string& s : strs) {
            string t = s;
            sort(t.begin(), t.end()); // 对字符串进行排序
            map[t].push_back(s); // 添加到映射中
        }

        vector<vector<string>> anagrams;
        for (auto& pair : map) {
            anagrams.push_back(pair.second); // 将哈希表中的值添加到结果中
        }

        return anagrams;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值