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;
    }
};
相关推荐
weixin_445054724 分钟前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
XXYBMOOO5 分钟前
基于 Qt 的 BMP 图像数据存取至 SQLite 数据库的实现
数据库·c++·qt
JNU freshman32 分钟前
C. Robin Hood in Town思考与理解
算法
GZX墨痕38 分钟前
从零学习直接插入排序
c语言·数据结构·排序算法
Susea&42 分钟前
数据结构初阶:双向链表
c语言·开发语言·数据结构
虾球xz1 小时前
游戏引擎学习第230天
c++·学习·游戏引擎
Net_Walke1 小时前
【C数据结构】 TAILQ双向有尾链表的详解
c语言·数据结构·链表
_x_w1 小时前
【17】数据结构之图及图的存储篇章
数据结构·python·算法·链表·排序算法·图论
anscos1 小时前
Actran声源识别方法连载(二):薄膜模态表面振动识别
人工智能·算法·仿真软件·actran
-优势在我2 小时前
LeetCode之两数之和
算法·leetcode