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;
    }
};
相关推荐
怕浪猫3 分钟前
Electron 系列文章封面图
算法·架构·前端框架
郝学胜_神的一滴1 小时前
CMake 021: IF 条件判据详诠
c++·cmake
徐小夕2 小时前
JitWord 3.0 正式发布,高精度Word异构解析+复杂组件兼容,打造web端协同Word编辑器
前端·vue.js·算法
_wyt00115 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
通信小呆呆17 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
benben04418 小时前
强化学习之DQN算法族(基于gymnasium开发)
算法
小小工匠18 小时前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾19 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
何以解忧,唯有..19 小时前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang