【leetcode】748. Shortest Completing Word 解题报告

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dpengwang/article/details/83006410

题目描述
在这里插入图片描述
记录这道题的目的在于第二种解法比较有启发意义
方法一:我的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

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

猜你喜欢

转载自blog.csdn.net/dpengwang/article/details/83006410