[LeetCode] Group Shifted Strings

249. Group Shifted Strings

We can shift a string by shifting each of its letters to its successive letter.

  • For example, “abc” can be shifted to be “bcd”.
    We can keep shifting the string to form a sequence.

  • For example, we can keep shifting “abc” to form the sequence: “abc” -> “bcd” -> … -> “xyz”.

Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
int compare(char ch1, char ch2) {
return (ch1 - ch2 + 26) % 26;
}

string buildRelativeSequence(string& s) {
string seq = "";
for(int i = 0; i < s.length() - 1; i++) {
seq += to_string(compare(s[i],s[i+1])) + "#";
}
return seq;
}
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<string, vector<string>> seq;
for(auto str : strings) {
string sequence = buildRelativeSequence(str);
seq[sequence].push_back(str);
}
vector<vector<string>> res;
for(auto [_, group] : seq) {
res.push_back(group);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/20/PS/LeetCode/group-shifted-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.