[Leetcode] 249. Group Shifted Strings 解题报告

题目

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:

"abc" -> "bcd" -> ... -> "xyz"

Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
A solution is:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

思路

我们将字符串的每个字符都减去一个统一的值,使得首字符变为‘a’,这样可以相互转换的字符就转化成了一个key,然后用map以这个key保存所有可以相互转换的字符串的集合,最后再输出结果。在实现中,我们既可以采用使用哈希表实现的unordered_map,也可以采用使用二叉搜索树实现的map。

代码

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        unordered_map<string, vector<string>> hash;
        for (auto s : strings) {
            hash[getGroupKey(s)].push_back(s);
        }
        vector<vector<string>> ret;
        for (auto it = hash.begin(); it != hash.end(); ++it) {
            vector<string> line(it->second.begin(), it->second.end());
            ret.push_back(line);
        }
        return ret;
    }
private:
    string getGroupKey(string &s) {
        string ret(s);
        int offset = s[0] - 'a';
        for (int i = 0; i < s.length(); ++i) {
            ret[i] = ret[i] - offset;
            if (ret[i] < 'a') {
                ret[i] += 26;
            }
        }
        return ret;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值