# 249. Group Shifted Strings

## 刷题内容

• 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.

Example:

Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]


## 解题方案

hash table存储pattern

class Solution(object):
def groupStrings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
table = {}
for w in strings:
pattern = ''
for i in range(1, len(w)):
if ord(w[i]) - ord(w[i - 1]) >= 0:
pattern += str(ord(w[i]) - ord(w[i - 1]))
else:
pattern += str(ord(w[i]) - ord(w[i - 1]) + 26)  ## 这是为了处理'az'和'ba'的情况

if pattern in table:
table[pattern].append(w)
else:
table[pattern] = [w]
return [table[pattern] for pattern in table]