题目链接:https://leetcode.com/problems/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"]
,
Return:
[ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ]
Note: For the return value, each inner list's elements must follow the lexicographic order.
思路:将每个字符串都转换成减去字符串首字符之后的字符串,这样可以相互转换的字符串就转化成了一个key,然后用map将以这个key保存所有可以相互转换字符串的集合.
代码如下:
class Solution { public: vector<vector<string>> groupStrings(vector<string>& strings) { unordered_map<string, vector<string>> mp; vector<vector<string>> result; for(auto str: strings) { string tem = str; for(int i =tem.size()-1; i >=0; i--) tem[i] = ('a'+(tem[i]-tem[0]+26)%26); mp[tem].push_back(str); } for(auto val: mp) { sort(val.second.begin(), val.second.end()); result.push_back(val.second); } return result; } };