Simple PYTHON beats 98%

  • 0
    class Solution(object):
        def groupStrings(self, strings):
            :type strings: List[str]
            :rtype: List[List[str]]
            map = {}
            ret = []
            for s in strings:
                keylist = []
                for i in xrange(1, len(s)):
                    offsetdiff = ( ord(s[i]) - ord(s[i-1]) ) % 26
                key = ','.join(keylist)
                if key in map:
                    map[key] = [s]
            # for key in map:
            #    ret.append(map[key])
            return [map[key] for key in map]

  • 0

    try this testcase ["am", "abd"], your solution would return [["am","abd"]] rather than the correct [["abd"],["am"]].
    Because your solution convert the keylist to string, which would make [12] and [1, 2] looks the same.

    One method to fix this bug is to subtitude keylist.append(str(offsetdiff)) with keylist.append(chr(offsetdiff + ord("a")). make the base-10 number as the base-26 number.

  • 0

    @han36 I see what you're saying I saw the same problem but forgot to update here. Thanks for catching that. My fix was to join with comma instead of empty string. See line

    key = ','.join(keylist)

Log in to reply

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