通过删除字母匹配到字典里最长单词
题目描述:
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
示例 :
输入:s = “abpcplea”, dictionary = [“ale”,“apple”,“monkey”,“plea”]
输出:“apple”
提示:
- 1 <= s.length <= 1000
- 1 <= dictionary.length <= 1000
- 1 <= dictionary[i].length <= 1000
- s 和 dictionary[i] 仅由小写英文字母组成
解法
比较直接的思路就是s与字典中的各个字符串逐个比对,边比对边更新最优解。
代码
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
res = ''
for p in dictionary:
i, j = 0, 0
while i < len(p) and j < len(s):
if p[i] == s[j]:
i += 1
j += 1
if i == len(p):
if i > len(res):
res = p
elif i == len(res):
res = min(res, p)
return res
测试结果
执行用时:540 ms, 在所有 Python3 提交中击败了 25.21% 的用户
内存消耗:16.2 MB, 在所有 Python3 提交中击败了 89.58% 的用户
说明
算法题来源:力扣(LeetCode)