7-line Python M*N solution with hashing


  • 0
    T
    from hashlib import sha1
    from string import ascii_lowercase
    from collections import defaultdict
    
    def groupAnagrams(self, strs):
        charmap = {}
        for c in ascii_lowercase:
            charmap[c] = int(sha1(c.encode('ascii')).hexdigest()[:7], 16)
    
        groups = defaultdict(list)
        for word in strs:
            groups[sum(charmap[c] for c in word)].append(word)
        
        return [groups[key] for key in groups]
    

    Increase the amount of the hexdigest kept for more certainty.


Log in to reply
 

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