Leetcode 524. Longest Word in Dictionary through Deleting
题目
解法:灵活运用双指针
总体思路比较简单,遍历d,判断每个d中的target是不是符合条件,并选择长度最长中lexicographical order最小的保存
这边主要对比一下python和C++在比较lexicographical order的不同。在python中,可以直接用sort函数对d进行排序来达到想要的效果,而在C++中,字符串直接进行比较就阔以了
python版本1:
这个版本在helper函数中就直接进行简单的双指针进行比较
class Solution:
def findLongestWord(self, s: str, d: List[str]) -> str:
def helper(s,target):
i = 0
j = 0
while i<len(s) and j<len(target):
if s[i] == target[j]:
i+=1
j+=1
else:
i+=1
return j==len(target)
d.sort(key=lambda x: [-len(x),x])
for c in d:
if helper(s,c):
return c
return ''
python版本2:
这个版本在helper函数中用了一点小技巧,对于target中的每个字符,直接定位这个字符在s中的位置,而后面的比较就只需要从s中第一次出现的这个位置之后的子字符串进行比较就可以,这样会快很多
class Solution:
def findLongestWord(self, s: str, d: List[str