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;
    }
};
相关推荐
芯眼5 分钟前
STM32启动文件详解(重点)
java·开发语言·c++·stm32·单片机·mybatis
天上路人1 小时前
AI神经网络降噪算法在语音通话产品中的应用优势与前景分析
深度学习·神经网络·算法·硬件架构·音视频·实时音视频
好吃的肘子1 小时前
MongoDB 应用实战
大数据·开发语言·数据库·算法·mongodb·全文检索
汉克老师2 小时前
GESP2025年3月认证C++二级( 第三部分编程题(1)等差矩阵)
c++·算法·矩阵·gesp二级·gesp2级
sz66cm2 小时前
算法基础 -- 小根堆构建的两种方式:上浮法与下沉法
数据结构·算法
緈福的街口2 小时前
【leetcode】94. 二叉树的中序遍历
算法·leetcode
顾小玙2 小时前
数据结构进阶:AVL树与红黑树
数据结构
小刘要努力呀!2 小时前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
joker D8882 小时前
【C++】深入理解 unordered 容器、布隆过滤器与分布式一致性哈希
c++·分布式·哈希算法
野曙3 小时前
快速选择算法:优化大数据中的 Top-K 问题
大数据·数据结构·c++·算法·第k小·第k大