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;
    }
};
相关推荐
CoderCodingNo35 分钟前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳103042 分钟前
C++:红黑树
开发语言·c++
大闲在人1 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
一切尽在,你来1 小时前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++
小熳芋1 小时前
443. 压缩字符串-python-双指针
算法
Charlie_lll1 小时前
力扣解题-移动零
后端·算法·leetcode
chaser&upper1 小时前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
weixin_499771551 小时前
C++中的组合模式
开发语言·c++·算法
iAkuya2 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
近津薪荼2 小时前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先