LeetCode 题解工作台
通过删除字母匹配到字典里最长单词
给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。 如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。 示例 1: 输入: s = "abpcplea", di…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们定义一个函数 $check(s, t)$,用于判断字符串 是否是字符串 的子序列。我们可以使用双指针的方法,初始化两个指针 和 分别指向字符串 和字符串 的开头,然后不断移动指针 ,如果 和 相等,则移动指针 ,最后判断 是否等于 的长度即可。若 等于 的长度,则说明 是 的子序列。 我们初始化答案字符串 为空字符串,然后遍历数组 中的每个字符串 ,如果 是 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] 输出:"apple"
示例 2:
输入:s = "abpcplea", dictionary = ["a","b","c"] 输出:"a"
提示:
1 <= s.length <= 10001 <= dictionary.length <= 10001 <= dictionary[i].length <= 1000s和dictionary[i]仅由小写英文字母组成
解题思路
方法一:判断子序列
我们定义一个函数 ,用于判断字符串 是否是字符串 的子序列。我们可以使用双指针的方法,初始化两个指针 和 分别指向字符串 和字符串 的开头,然后不断移动指针 ,如果 和 相等,则移动指针 ,最后判断 是否等于 的长度即可。若 等于 的长度,则说明 是 的子序列。
我们初始化答案字符串 为空字符串,然后遍历数组 中的每个字符串 ,如果 是 的子序列,并且 的长度大于 的长度,或者 的长度等于 的长度且 字典序小于 ,则更新 为 。
时间复杂度 ,其中 是字符串列表的长度,而 和 分别是字符串 的长度和字符串列表中字符串的平均长度。空间复杂度 。
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
def check(s: str, t: str) -> bool:
m, n = len(s), len(t)
i = j = 0
while i < m and j < n:
if s[i] == t[j]:
i += 1
j += 1
return i == m
ans = ""
for t in dictionary:
if check(t, s) and (len(ans) < len(t) or (len(ans) == len(t) and ans > t)):
ans = t
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate effectively uses two-pointer scanning to match characters between `s` and dictionary words.
- question_mark
Look for optimization strategies, especially how they handle lexicographical order and early termination.
- question_mark
Assess how the candidate handles edge cases, such as when no words can be formed from `s`.
常见陷阱
外企场景- error
Failing to account for lexicographical order when multiple words of the same length are valid.
- error
Not using the two-pointer method efficiently, leading to unnecessary scans of `s`.
- error
Overcomplicating the problem with excessive nested loops instead of leveraging simple pointer movement.
进阶变体
外企场景- arrow_right_alt
The problem could be extended to handle uppercase letters or include non-English characters in the string and dictionary.
- arrow_right_alt
A variant could involve finding the second longest valid word if the longest one has multiple occurrences.
- arrow_right_alt
The task might be modified to allow for insertion or replacement of characters instead of only deletions.