LeetCode 249. 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"]
]

------------------------------------------------------------------

雖然過了,操作有點長:

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()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章