Group Shifted Strings

Problem: Group Shifted Strings

We can observe and prove that shifted strings have same difference between adjacent characters. For example, difference between adjacent characters for "a, b, c" is (1, 1). So does "b, c, d" and "x, y, z". We can use this value as keys in hash table and store shifted strings in group.

Code in Python:

from collections import defaultdict

class Solution(object):
    def groupStrings(self, strings):
        """
        :type strings: List[str]
        :rtype: List[List[str]]
        """
        dict = defaultdict(list)
        for string in strings:
            steps, prev = [0], string[0]
            for i in xrange(1, len(string)):
                diff = ord(string[i]) - ord(string[i-1])
                if diff < 0:
                    diff += 26
                steps.append(diff)
            dict[str(steps)].append(string)
        ans = []
        for steps in dict:
            ans.append(sorted(dict[steps]))
        return ans

results matching ""

    No results matching ""