Python solution beating 95%


  • 0
    U
    class Solution(object):
        def groupStrings(self, strings):
            """
            :type strings: List[str]
            :rtype: List[List[str]]
            """
            hash = {}
            zero = []
            single = []
            for string in strings:
                if not string:
                    zero.append(string)
                elif len(string) == 1:
                    single.append(string)
                else:
                    key = ''
                    for index in range(1, len(string)):
                        val = ord(string[index]) - ord(string[index - 1])
                        key += str(26 + val if val < 0 else val)
                    if key not in hash:
                        hash[key] = [string]
                    else:
                        hash[key].append(string)
            hash = hash.values() 
            if single:
                hash.append(single)
            if zero:
                hash.append(zero)
                
            return hash
                        
    

  • 1
    J

    I think there might be cases wrong with key defined like this.
    For example: "ap" would be put into the same group with "abg"
    since "ap" --> "15", "abg" --> "15"
    while they belong to different group.


Log in to reply
 

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