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"]
]
------------------------------------------------------------------
雖然過了,操作有點長:
from collections import defaultdict
class Solution:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
def get_key(s):
res = ''
delta = ord(s[0])-ord('a')
for ch in s:
if (ord(ch)-delta >= ord('a')):
res += chr(ord(ch)-delta)
else:
res += chr(ord(ch)-delta+26)
return res
res = []
dic = defaultdict(list)
for s in strings:
key = get_key(s)
dic[key].append(s)
for k,v in dic.items():
res.append(sorted(v))
return res
從Discussion學的精簡codes:
from collections import defaultdict
class Solution:
def groupStrings(self, strings):
groups = collections.defaultdict(list)
for s in strings:
groups[tuple((ord(c) - ord(s[0])) % 26 for c in s)] += s,
return groups.values()