【leetcode】748. Shortest Completing Word

题目描述
【leetcode】748. Shortest Completing Word_第1张图片
记录这道题的目的在于第二种解法比较有启发意义
方法一:我的low B做法

class Solution:
    def shortestCompletingWord(self, licensePlate, words):
        """
        :type licensePlate: str
        :type words: List[str]
        :rtype: str
        """
        characterSet = []
        for i in licensePlate:
            if i.isalpha():
                characterSet.append(i.lower())
        res = "aaaaaaaaaaaaaaaaaaaa"
        for word in words:
            if self.helper(word,characterSet) and len(word) < len(res):
                res = word
        return res
    def helper(self,word,characterSet):
        dictionary = {}
        for i in word:
            if i in dictionary:
                dictionary[i] +=1
            else:
                dictionary[i] =1
        for i in characterSet:
            if i in dictionary and dictionary[i]>=1:
                dictionary[i] -=1
            else:
                return False
        return True

方法二:
看了discuss后

class Solution:
    def shortestCompletingWord(self, licensePlate, words):
        """
        :type licensePlate: str
        :type words: List[str]
        :rtype: str
        """
        prime =[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103]
        licenseNum =1
        for i in licensePlate:
            if i.isalpha():
                index = ord(i.lower())-97
                licenseNum *= prime[index]
        res ="aaaaaaaaaaaaaaaaa"
        for word in words:
            count =1
            for char in word:
                count *= prime[ord(char)-97]
            if count % licenseNum==0 and len(word) < len(res):
                res =word
        return res

启发:可以考虑用质数表来代替哈希表来解决一些问题

你可能感兴趣的:(LeetCode,LeetCode)