Group Anagrams

字谜分组算法
本文介绍了一种使用unordered_map对字符串数组中字谜进行分组的高效算法。通过排序每个单词来确定其pattern,以此作为key,将相同pattern的单词归纳到同一vector中,最终返回所有归纳好的单词组。

1,题目要求

Given an array of strings, group anagrams together.

Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:

[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

All inputs will be in lowercase.
The order of your output does not matter.

给定一个字符串数组,将字谜组合在一起。

2,题目思路

对于这道题,是要求将所含字符相同的单词归纳在一起。

因此,我们的思路是利用unordered_map来对每个单词进行遍历,解决题目所要求的问题。

其中:

  • key是单词的pattern,利用对每个单词进行sort一下来确定pattern。
  • value是一个vector,保存对应key所对应的单词。

3,代码实现

static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> pattern_Instance;
        vector<vector<string>> res;
        
        if(strs.size() == 0)
            return res;
        
        for(auto &s : strs)
        {
            string tmp = s;
            sort(tmp.begin(), tmp.end());
            pattern_Instance[tmp].push_back(s);
        }
        
        for(auto &s : pattern_Instance)
            res.push_back(s.second);
        
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值