42ms 98.47% Python solution, very easy to understand


  • 0
    K
    class Solution(object):
        def groupStrings(self, strings):
            """
            :type strings: List[str]
            :rtype: List[List[str]]
            """
            dic = collections.defaultdict(list)
            for s in strings:
                if len(s) == 1:
                    dic[(1)].append(s)
                else:
                    seq = (1,)
                    for i in xrange(1, len(s)):
                        d = ord(s[i]) - ord(s[i-1])
                        if d < 0: d += 26
                        seq += (d,)
                    dic[seq].append(s)
            return dic.values()
    

    We simply shift every string to let it start with letter 'a' and use a dictionary to store in it in buckets (key being shifted sequence and value being original string). Finally we return the values in that dictionary. ord function is helpful here since ord('a') = 97 and ord('z') = 122


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.