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;
    }
};
相关推荐
Dave.B2 分钟前
用【vtk3DLinearGridCrinkleExtractor】快速提取3D网格相交面
算法·3d·vtk
一起养小猫3 分钟前
LeetCode100天Day1-字符串匹配与Z字形变换
java·leetcode
yaoh.wang10 分钟前
力扣(LeetCode) 1: 两数之和 - 解法思路
python·程序人生·算法·leetcode·面试·跳槽·哈希算法
又是忙碌的一天12 分钟前
二叉树的构建与增删改查(2) 删除节点
数据结构
Code Slacker26 分钟前
LeetCode Hot100 —— 滑动窗口(面试纯背版)(四)
数据结构·c++·算法·leetcode
brave and determined30 分钟前
CANN训练营 学习(day8)昇腾大模型推理调优实战指南
人工智能·算法·机器学习·ai实战·昇腾ai·ai推理·实战记录
总爱写点小BUG1 小时前
打印不同的三角形(C语言)
java·c语言·算法
yaoh.wang1 小时前
力扣(LeetCode) 27: 移除元素 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
2401_841495641 小时前
【自然语言处理】中文 n-gram 词模型
人工智能·python·算法·自然语言处理·n-gram·中文文本生成模型·kneser-ney平滑
San302 小时前
从零到一:彻底搞定面试高频算法——“列表转树”与“爬楼梯”全解析
javascript·算法·面试