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;
    }
};
相关推荐
洋不写bug8 分钟前
链表面试笔试经典题目详细解析,题目多解法,复杂度分析
数据结构·链表·面试
s_w.h1 小时前
【 刷题 】双指针
算法
啥都想学点的研究生1 小时前
一篇文章讲清楚:K-Means聚类算法
算法·kmeans·聚类
白狐_7981 小时前
408 数据结构|KMP做题方法:next、nextval和高频易错点
数据结构·算法
月华路1 小时前
《模型不玄学》第20章 两种评估视角
人工智能·算法·机器学习
禹凕2 小时前
快速幂算法详解与实战
python·算法
xxwl5852 小时前
高斯消元法异或版
人工智能·算法·机器学习
sylviiiiiia2 小时前
leetcode hot 100
python·算法·leetcode
励志不掉头发的内向程序员2 小时前
【LibreCAD 2D架构】从鼠标点击到图形创建:RS_ActionDrawLine交互流程与状态机解析
开发语言·c++·qt·学习·系统架构·计算机外设·交互
OPEN-F2 小时前
ROS2系列教程:Gazebo插件(关节控制/IMU/激光雷达)
c++·python·数码相机·算法·机器人