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"]
,
[ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"]]
class Solution {public: vector> groupStrings(vector & strings) { unordered_map >mp; for(auto str:strings){ string t = shifted(str); mp[t].push_back(str); } for(auto it = mp.begin();it!=mp.end();it++) sort(it->second.begin(),it->second.end()); vector > res; for(auto it = mp.begin();it!=mp.end();it++) res.push_back(it->second); return res; }private: string shifted(string str) { string t; int diff=0; for(int i = 1;i