Fork me on GitHub

Group Shifted Strings

Description

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:

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

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

Example:

1
2
3
4
5
6
7
8
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]

Solution

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 {
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<int, vector<string>> mapping;
for(auto& item : strings) {
int hashValue = 0;
int base = 1;
for (int i = 1; i < item.size(); ++i){
hashValue += base * distance(item[i-1], item[i]);
base *= 26;
}
mapping[hashValue].push_back(item);
}

vector<vector<string>> ret;
for(auto& item : mapping) {
ret.push_back(item.second);
}

return ret;
}

int distance(char a, char b) {
return b - a + (a < b ? 0 : 26);
}
};