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;
    }
};
相关推荐
报错小能手11 小时前
C++笔记——STL map
c++·笔记
思麟呀12 小时前
Linux的基础IO流
linux·运维·服务器·开发语言·c++
星释12 小时前
Rust 练习册 :Pythagorean Triplet与数学算法
开发语言·算法·rust
星释12 小时前
Rust 练习册 :Nth Prime与素数算法
开发语言·算法·rust
多喝开水少熬夜13 小时前
Trie树相关算法题java实现
java·开发语言·算法
QT 小鲜肉13 小时前
【QT/C++】Qt定时器QTimer类的实现方法详解(超详细)
开发语言·数据库·c++·笔记·qt·学习
WBluuue13 小时前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp13 小时前
牛客网华为在线编程题
算法
lkbhua莱克瓦2414 小时前
Java基础——集合进阶用到的数据结构知识点1
java·数据结构·笔记·github
呆瑜nuage14 小时前
C++之红黑树
c++