LeetCode49. 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.

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"]

Constraints:

1 <= strs.length <= 104

0 <= strsi.length <= 100

strsi consists of lowercase English letters.

二、题解

cpp 复制代码
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        int n = strs.size();
        unordered_map<string,vector<string>> map;
        for(int i = 0;i < n;i++){
            string s = strs[i];
            sort(s.begin(),s.end());
            map[s].emplace_back(strs[i]);
        }
        vector<vector<string>> res;
        //遍历所有的key
        for(auto it = map.begin();it != map.end();it++){
            res.emplace_back(it->second);
        }
        return res;
    }
};
相关推荐
吴长建先生重名了42 分钟前
GitHub Actions部署报表系统踩坑记:幂等性与限
算法
贝壳6901 小时前
一个2026年2月才上传的库,凭什么敢碰2009年就有人写烂的题目
算法
文丑颜不良啊2 小时前
LeetCode2901~2920题目解析
java·leetcode
贝壳6902 小时前
同一道三亿位选型题,三个AI给了我三个答案,我把它们拉进同一台机器复跑
算法
汉克老师3 小时前
《从C++小白到算法高手:GESP 1—8级成长地图》第一讲:认识GESP——从编程新手到算法探索者
c++·gesp·信息学竞赛·小学生学c++
文丑颜不良啊4 小时前
LeetCode2861~2880题目解析
java·leetcode
岑梓铭4 小时前
《考研408数据结构》第八章(排序)复习笔记
数据结构·笔记
晴天的雨.9924 小时前
【C++】继承篇
java·开发语言·c++
青少儿编程课堂4 小时前
蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园大富翁经营闯关解析
c++·python·算法·bfs·信息学竞赛
another heaven4 小时前
【C/C++ 第一次跨越(上):用 C++11/14 停止制造新的旧代码】
c语言·c++·制造