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 <= strs[i].length <= 100

strs[i] 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;
    }
};
相关推荐
沐怡旸9 分钟前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
NAGNIP44 分钟前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队2 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
River4163 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥6 小时前
C++ std::set
c++
Fanxt_Ja6 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下6 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶6 小时前
算法 --- 字符串
算法
博笙困了7 小时前
AcWing学习——差分
c++·算法
NAGNIP7 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法