LintCode 772: Group Anagrams

本文介绍了一种用于将字符串数组中所有字谜(anagrams)进行分组的高效算法。通过使用map结构,算法能够快速识别并分组具有相同字符组成的字符串,即使在大规模数据集上也能保持良好的性能。
  1. Group Anagrams

Given an array of strings, group anagrams together.

Example
Example 1:

Input:
[“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
Output:
[[“ate”,“eat”,“tea”],
[“bat”],
[“nat”,“tan”]]
Example 2:

Input:
[“eat”,“nowhere”]
Output:
[[“eat”],
[“nowhere”]]
Notice
All inputs will be in lower-case.

解法1:我用的map of map。
注意:
1)返回一个空的2D vector可以用{{}}。
2) map的first和second都不能加(),即不能用first(),直接用first就可。
代码如下:

class Solution {
public:
    /**
     * @param strs: the given array of strings
     * @return: The anagrams which have been divided into groups
     */
    vector<vector<string>> groupAnagrams(vector<string> &strs) {
        int n = strs.size();
        vector<vector<string>> result;
        if (n == 0) return {{}};

        map<map<char, int>, vector<string>> mp;
        
        for (int i = 0; i < n; ++i) {
            map<char, int> dict;
            int m = strs[i].size();
            for (int j = 0; j < m; ++j) {
                dict[strs[i][j]]++;
            }
            mp[dict].push_back(strs[i]);
        }
        
        for (auto m : mp) {
            result.push_back(m.second);
        }
        
        return result;
    }
};

二刷: 注意我们可以把vector 用string来表示,从而简化代码,当然这个string是会显示乱码,不过我们只需要用它在map里面做第一项来处理就可以了。
//string(freqTable.begin(), freqTable.end())

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        int n = strs.size();
        //map<vector<int>, vector<string>> mp; //<freqTable, vector<string>>
        map<string, vector<string>> mp; //<string, vector<string>>
        for (auto str : strs) {
            vector<int> freqTable(26, 0);
            for (auto c : str) {
                freqTable[c - 'a']++;
            }
            mp[string(freqTable.begin(), freqTable.end())].push_back(str);
        }
        for (auto freq : mp) {
            res.push_back(freq.second);
        }
        return res;
    }
};
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值