2.字母异位词分组

1.题目描述

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。字母异位词指的是由相同字母组成但排列顺序不同的字符串,例如 "eat""tea"

示例 1:

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

输出:[["bat"],["nat","tan"],["ate","eat","tea"]]

解释:

  • 在 strs 中没有字符串可以通过重新排列来形成 "bat"
  • 字符串 "nat""tan" 是字母异位词,因为它们可以重新排列以形成彼此。
  • 字符串 "ate""eat""tea" 是字母异位词,因为它们可以重新排列以形成彼此。

2.解题思路

可以这么理解哈希表的结构,但并非这样

3.代码

cpp 复制代码
#include <iostream>
#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>> mp;

        // 遍历 strs
        for (int i = 0; i < strs.size(); ++i) {
            string str = strs[i];
            string key = str;
            sort(key.begin(), key.end());
            mp[key].push_back(str);
        }

        vector<vector<string>> ans;

        // 遍历 mp
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            ans.push_back(it->second);
        }

        return ans;
    }
};

int main() {
    // 示例输入
    vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};

    // 创建 Solution 对象并调用函数
    Solution sol;
    vector<vector<string>> result = sol.groupAnagrams(strs);

    // 打印结果
    cout << "[";
    for (int i = 0; i < result.size(); ++i) {
        cout << "[";
        for (int j = 0; j < result[i].size(); ++j) {
            cout << "\"" << result[i][j] << "\"";
            if (j != result[i].size() - 1) {
                cout << ",";
            }
        }
        cout << "]";
        if (i != result.size() - 1) {
            cout << ",";
        }
    }
    cout << "]" << endl;

    return 0;
}

4.代码解析

cpp 复制代码
for (int i = 0; i < strs.size(); ++i) {
            string str = strs[i];
            string key = str;
            sort(key.begin(), key.end());
            mp[key].push_back(str);
        }

遍历strs,如先遍历eat,然后排序为aet,以aet为key将原来的str也就是eat作为value。依次遍历完整个strs。

复制代码
   vector<vector<string>> ans;

        // 遍历 mp
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            ans.push_back(it->second);
        }

遍历每一个key,从aet开始遍历,将对应的所有value加入到ans中

相关推荐
JaneHan_6 小时前
STM32CubeMX+HAL+Keil5 PWM呼吸灯
c语言·stm32·单片机
郝学胜-神的一滴6 小时前
[简化版 GAMES 101] 计算机图形学 04:二维变换上
c++·算法·unity·godot·图形渲染·unreal engine·cesium
爱编码的小八嘎6 小时前
C语言完美演绎7-7
c语言
来日可期13147 小时前
C/C++ 反常识记录(1)—— 那些容易踩坑的语法细节
c语言·开发语言·c++
计算机安禾7 小时前
【数据结构与算法】第41篇:图论(五):拓扑排序与关键路径
c语言·数据结构·c++·算法·图论·visual studio
身如柳絮随风扬7 小时前
Redis中的哈希槽怎么理解
redis·哈希算法
Q741_1477 小时前
每日一题 力扣 1320. 二指输入的的最小距离 动态规划 C++ 题解
c++·算法·leetcode·动态规划
实心儿儿7 小时前
C++ —— C++11(2)
开发语言·c++
加油JIAX7 小时前
C++11特性
c++
itman3017 小时前
Windows环境下编译运行C语言程序的方法及工具选择
c语言·visualstudio·mingw·编译器·windows环境