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"]
]
我们要有一个统一的标准,将每个单词都转化成以z开头的单词,这样才能判断两个单词是否是同一组。
-
写一个函数
convertToZstart
实现上面的功能。 -
用一个
defaultdict
来实现分组保存的功能,其中键
为z开头的单词,值
为该组的所有单词(一个列表)。from collections import defaultdict class Solution: def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ # a的ascii码是97 z的ascii码是122 def convertToZstart(word): step = ord('z') - ord(word[0]) # step为第一个字母转化成z需要的步数。 return "".join(map(lambda c: chr(ord(c) + step if ord(c) + step < 123 else ord(c) + step - 26), word)) # 如果当前字母加上step后大于ord(z),需要减去26。 # 用一个defaultdict来存储z开头的字符串。 dd = defaultdict(list) for word in strings: dd[convertToZstart(word)].append(word) return [value for value in dd.values()]