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; } };
|