题目描述
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。 如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
输出:"apple"
示例 2:
输入:s = "abpcplea", dictionary = ["a","b","c"]
输出:"a"
解题思路: 自定义排序 + 双指针
- 主要实现字符串s通过删除一定字符后, 是否可以变成数组中的元素
- 要求返回长度最长且字典序最小, 我们可以直接将原数组的数据进行排序, 直接变成长度递减的字典序, 这样可以直接遍历数组找到的第一个就是最终结果
- 对于步骤一, 我们可以使用双指针法, 对2个字符串进行遍历, 进行比对
示例代码
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
def checkItem(item: str) -> bool:
# 容错判断
if len(item) > len(s):
return False
# 双指针进行判断
i, j = 0, 0
while i < len(item):
if j < len(s) and item[i] == s[j]:
i += 1
j += 1
if i >= len(item):
return True
if j >= len(s):
return False
return False
# 对原数组进行自定义排序
dictionary.sort(key=lambda x: (-len(x), x))
# 排序后的原数组进行遍历
for item in dictionary:
if checkItem(item):
return item
return ''