Group Shifted Strings -- LeetCode

本文介绍了一种针对字符串移位操作的分组算法实现。该算法通过将字符串中的每个字符向后移动一位并进行特定转换,从而形成一组新的字符串。通过对这些字符串进行分组,可以找出属于同一移位序列的所有字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"]
]
 1 class Solution {
 2 public:
 3     string help(string word) {
 4         for (int i = 1, n = word.size(); i < n; i++) {
 5             word[i] = word[i] - word[0] + 'a';
 6             while (word[i] < 'a') word[i] += 26;
 7         }
 8         word[0] = 'a';
 9         return word;
10     }
11     vector<vector<string>> groupStrings(vector<string>& strings) {
12         unordered_map<string, int> dict;
13         vector<vector<string> > res;
14         for (int i = 0, n = strings.size(); i < n; i++) {
15             string base = help(strings[i]);
16             if (dict.count(base) == 0) {
17                 dict.insert(make_pair(base, res.size()));
18                 vector<string> subGroup(1, strings[i]);
19                 res.push_back(subGroup);
20             }
21             else res[dict[base]].push_back(strings[i]);
22         }
23         return res;
24     }
25 };

 

转载于:https://www.cnblogs.com/fenshen371/p/5769925.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值