249. Group Shifted Strings
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"] ]
class Solution { public: vector<vector<string>> groupStrings(vector<string>& strings) { unordered_map<string,vector<string>>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<vector<string>> 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<str.size();i++) { diff = str[i]-str[i-1]; if(diff<0) diff+=26; t+=to_string(diff)+"#"; } return t; } };