LC化元归一

Catalog:
[Uber] LC 49 Group Anagram

[Uber] LC 49 Group Anagram
把相同字母排列不同的单词放在一起,返回list of list of strings.
方法一:sort作为base! 直接,Time Complexity: O(NKlogK),K是最长的string, 排序要KlogK.

class Solution(object):
    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for s in strs:
            ans[tuple(sorted(s))].append(s)
        return ans.values()

方法二:Count26字母频率!

class Solution:
    def groupAnagrams(strs):
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            ans[tuple(count)].append(s)
        return ans.values()

utilizing unique prime multiplication,beat 91%

class Solution:
    def groupAnagrams(self,strs):
        primes = {'a': 2, 
                  'b': 3, 
                  'c': 5, 
                  'd': 7, 
                  'e': 11, 
                  'f': 13,
                  'g': 17,
                  'h': 19,
                  'i': 23,
                  'j': 29,
                  'k': 31,
                  'l': 37,
                  'm': 41,
                  'n': 43,
                  'o': 47,
                  'p': 53,
                  'q': 59,
                  'r': 61,
                  's': 67, 
                  't': 71,
                  'u': 73,
                  'v': 79,
                  'w': 83,
                  'x': 89,
                  'y': 97,
                  'z': 101
                 }
        
        
        ans = collections.defaultdict(list)
        
        for string in strs:
            product = 1
            
            for character in string:
                product = primes[character] * product
            
            ans[product].append(string)
            
        return ans.values()

You can also save prime numbers in an array and use character - 'a' to fetch the data!

你可能感兴趣的:(LC化元归一)