题目
题解
思路:双指针,s中包含进dictionary中当前元素,就可以开始判断结果:当前的ch更大就可以替换,或者长度相等时判断字母序;
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
res = ""
for ch in dictionary:
i = j = 0
while i < len(s) and j < len(ch):
if s[i] == ch[j]:
j += 1
i += 1
if j == len(ch):
if len(ch) > len(res) or (len(ch) == len(res) and ch < res):
res = ch
return res
本文介绍了一种使用双指针技巧解决字符串`s`中最长单词在`dictionary`中查找的问题。通过逐字符比较并更新最长匹配,展示了如何在O(n)时间内找到`s`中与字典中单词长度相同或更长且字母顺序优的单词。

被折叠的 条评论
为什么被折叠?



