最短补全词
题目要求:
给定一个字符串牌照 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中的 最短补全词 。
如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为 补全词 。在所有完整词中,最短的单词我们称之为 最短补全词 。
单词在匹配牌照中的字母时要:
- 忽略牌照中的数字和空格。
- 不区分大小写,比如牌照中的 “P” 依然可以匹配单词中的 “p” 字母。
- 如果某个字母在牌照中出现不止一次,那么该字母在补全词中的出现次数应当一致或者更多。
- 例如:licensePlate = “aBc 12c”,那么它由字母 ‘a’、‘b’ (忽略大写)和两个 ‘c’ 。可能的 补全词 是 “abccdef”、“caaacab” 以及 “cbca” 。
题目数据保证一定存在一个最短补全词。当有多个单词都符合最短补全词的匹配条件时取单词列表中最靠前的一个。
解题思路:
看着题目要求确实很多,但是仔细分析下来,一步一步实现,还是比较容易的。我就是按照它的要求一步一步做的。具体解题思路见注释,写的非常详细了。
题解代码:
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
#去除字符串牌照 licensePlate中的数组和空格;
for i in range(10):
licensePlate = licensePlate.replace(str(i),"")
licensePlate = licensePlate.replace(" ","")
#题目要求不区分大小写,且字符串数组 words中的词全为小写。将licensePlate中的大写字母全部转化为小写字母;
for i in range(len(licensePlate)):
if ord(licensePlate[i]) <91:
licensePlate = licensePlate.replace(licensePlate[i], chr(ord(licensePlate[i])+32))
#构建一个用来保存补全词的数组
bqc = []
#遍历字符串数组 words。获取符合条件的补全词
for i in range(len(words)):
#middle用来获取每个单词,在符合条件的情况下将其保存在补全词数组中
middle = words[i]
#遍历拍照中的每个字母
for j in range(len(licensePlate)):
#判断是否在单词中,在则删除单词中的这个元素一次
if licensePlate[j] in words[i]:
words[i] = words[i].replace(licensePlate[j],"",1)
#否则直接跳出当前循环(说明不是补全词)
else:
break
#当遍历到拍照中的最后一个词,且符合条件,则将这个单词保存在补全词数组中
if j == len(licensePlate)-1:
bqc.append(middle)
#遍历补全词数组,获取最短补全词
##构建一个存放最短补全词的变量,初始值为补全词数组的第一个元素
a = bqc[0]
##判断之后的词的长度与初始值长度的大小,小则更新最短补全词
for i in bqc:
if len(a)>len(i):
a = i
#返回最短补全词
return a
我的leetcode.
(“Women's value has been under-recognized for far too long.(女性的力量被低估太久了)
”FIGHTING. . . .)