【每日一题】Leetcode:524.通过删除字母匹配到字典里最长单词
- 给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。
- 示例 1:
输入:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
输出:
"apple"
- 示例 2:
输入:
s = "abpcplea", d = ["a","b","c"]
输出:
"a"
-
说明:
1、所有输入的字符串只包含小写字母。
2、字典的大小不会超过 1000。
3、所有输入的字符串长度不会超过 1000。 -
我的思路:
遇到的两个问题:
1、
理解:
2、
理解:
代码:
class Solution:
def findLongestWord(self, s: str, d: List[str]) -> str:
dLen = len(d)
index, indexlen, flag = 0, 0, 0 # flag是判断有无匹配的标志
for i in range(dLen):
strLen = len(d[i])
cur = 0
for j in s:
if(d[i][cur] == j):
cur += 1
if(cur == strLen):
flag = 1
if(indexlen < strLen or (indexlen == strLen and d[index] > d[i])):
index = i
indexlen = strLen
break
if(flag == 1):
return d[index]
return ""
- 优化
代码:
class Solution:
def findLongestWord(self, s: str, d: List[str]) -> str:
d.sort(key = lambda x: (-len(x), x))
for word in d:
index = 0
for ch in word:
index = s.find(ch, index) # find输出-1:False
if(index == -1):
break
else:
index += 1 # 从下一个位置继续查
else: # break结束不会执行,正常结束会执行
return word
return ''
分析:
- 新知识:
Python的find()函数:
用于查找字符串中是否包含对应子串。