【leetcode】748. Shortest Completing Word 解題報告
阿新 • • 發佈:2018-12-14
題目描述 記錄這道題的目的在於第二種解法比較有啟發意義 方法一:我的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
啟發:可以考慮用質數表來代替雜湊表來解決一些問題