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"] ]
Analyse: keep the diff between each character in the string. Put the strings with same diff in the same vector.
Runtime: 6ms
1 class Solution { 2 public: 3 vector<vector<string>> groupStrings(vector<string>& strings) { 4 unordered_map<string, vector<string> > groups; 5 for (string s : strings) { 6 if (s.size() == 1) { 7 groups["-"].push_back(s); 8 } else { 9 string tempGap; 10 for (int i = 1; i < s.size(); i++) { 11 if (s[i] > s[i - 1]) 12 tempGap += to_string(s[i] - s[i - 1]); 13 else 14 tempGap += to_string(26 + (s[i] - s[i - 1])); 15 } 16 groups[tempGap].push_back(s); 17 } 18 } 19 20 vector<vector<string> > result; 21 for (auto ite = groups.begin(); ite != groups.end(); ite++) { 22 vector<string> tempStrings = ite->second; 23 result.push_back(vector<string>()); 24 for (auto s : tempStrings) { 25 result.back().push_back(s); 26 } 27 } 28 return result; 29 } 30 };