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;
    }
};
相关推荐
Jerry1 小时前
LeetCode 151. 反转字符串中的单词
算法
gugucoding2 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL3 小时前
我的数据结构3——链表(link list)
数据结构·链表
a1117764 小时前
LM 算法迭代过程动画演示(SLAM)
算法
头茬韭菜4 小时前
Context 的生死抉择:四层压缩、截断算法与 Session Memory
算法·ai
Jerry4 小时前
LeetCode 541. 反转字符串 II
算法
Jerry4 小时前
LeetCode 344. 反转字符串
算法
cookies_s_s5 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
搞科研的小刘选手5 小时前
【香港大学主办&IEEE出版】第六届计算机视觉、应用与算法国际学术会议(CVAA 2026)
算法·计算机视觉·应用·学术会议
Java小白笔记5 小时前
Codex config.toml配置实战指南
人工智能·算法·chatgpt·ai编程·集成学习