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"] ]
1 class Solution { 2 public: 3 string help(string word) { 4 for (int i = 1, n = word.size(); i < n; i++) { 5 word[i] = word[i] - word[0] + ‘a‘; 6 while (word[i] < ‘a‘) word[i] += 26; 7 } 8 word[0] = ‘a‘; 9 return word; 10 } 11 vector<vector<string>> groupStrings(vector<string>& strings) { 12 unordered_map<string, int> dict; 13 vector<vector<string> > res; 14 for (int i = 0, n = strings.size(); i < n; i++) { 15 string base = help(strings[i]); 16 if (dict.count(base) == 0) { 17 dict.insert(make_pair(base, res.size())); 18 vector<string> subGroup(1, strings[i]); 19 res.push_back(subGroup); 20 } 21 else res[dict[base]].push_back(strings[i]); 22 } 23 return res; 24 } 25 };
时间: 2024-07-28 20:37:40