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;
    }
};
相关推荐
信奥卷王4 小时前
[GESP202503 六级] 环线(含视频)
算法
傲世仙尊4 小时前
赋值运算符重载-从无到有与从有到有六大函数收官
c++
CQU_JIAKE4 小时前
10.15【A】
算法
晴天的雨.9924 小时前
【C++】模板进阶
开发语言·c++·算法
Shadow(⊙o⊙)5 小时前
仿muduo实现高并发服务器——时间轮timewheel.cpp
c语言·c++
木井巳5 小时前
【动态规划】三步问题
java·算法·leetcode·动态规划·推荐算法
楚识科技5 小时前
手写 OCR 识别技术深度解析:从算法原理到政企级落地实现
算法·ocr
码爸7 小时前
b树详细介绍与示例
数据结构·b树
leobertlan13 小时前
痛苦系列 | DSP-03 跨越单位圆:Z变换与零极点分析
算法·程序员
蛋蛋的就会顺顺的13 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣