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;
    }
};
相关推荐
凤年徐28 分钟前
C++类和对象(上):从设计图到摩天大楼的构建艺术
c语言·开发语言·c++·类和对象
lifallen29 分钟前
Kafka 内存池MemoryPool 设计
数据结构·kafka·apache
RTC老炮1 小时前
webrtc弱网-LossBasedBandwidthEstimation类源码分析与算法原理
网络·算法·webrtc
豆浩宇1 小时前
Conda环境隔离和PyCharm配置,完美同时运行PaddlePaddle和PyTorch
人工智能·pytorch·算法·计算机视觉·pycharm·conda·paddlepaddle
一只鱼^_1 小时前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
小刘的AI小站2 小时前
leetcode hot100 二叉搜索树
算法·leetcode
自信的小螺丝钉2 小时前
Leetcode 876. 链表的中间结点 快慢指针
算法·leetcode·链表·指针
红豆怪怪2 小时前
[LeetCode 热题 100] 32. 最长有效括号
数据结构·python·算法·leetcode·动态规划·代理模式
参.商.2 小时前
【Day21】146.LRU缓存 (Least Recently Used)
leetcode·缓存·golang
愚润求学2 小时前
【贪心算法】day6
c++·算法·leetcode·贪心算法