LeetCode 249. Group Shifted Strings
2017-01-07 09:25:00       个评论    来源：xinqrs01的博客
我要投稿

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.

1. 放到一组的string遵循一个pattern，我们可以遍历所有string，把每个string的相邻字母的差值作为pattern，例如：“abc”的pattern就是“11”，然后把这个pattern保存在hashtable中；当遇到“bcd”,先计算pattern为”11”,然后查询hash表，如果存在，就把”bcd”存在unordered_map
2. 注意的是，”al”的pattern也是”11”,为了区分这两者，需要添加逗号分隔，即：”abc”pattern=”1,1”，”al”的pattern=”11”。
3. 这题需要提取和保存的信息是：每个string的pattern。
4. 刚拿到题，我的思路是：每个string和所有string比较，这样复杂度就是o(n^2),而用提取pattern并用hash保存，复杂度可降低o(n)

```vector> groupStrings(vector& strings) {
unordered_map> mm;

for(auto&cur:strings){
string pattern=" ";
for(auto&k:cur)
pattern= pattern+to_string(((k-cur[0])+26)%26)+',';
mm[pattern].push_back(cur);
}
vector> res;
for(auto it:mm){
vector vect=it.second;
sort(vect.begin(),vect.end());
res.push_back(vect);
}
return res;
}```