LeetCode 题解工作台
字符串中的额外字符
给你一个下标从 0 开始的字符串 s 和一个单词字典 dictionary 。你需要将 s 分割成若干个 互不重叠 的子字符串,每个子字符串都在 dictionary 中出现过。 s 中可能会有一些 额外的字符 不在任何子字符串中。 请你采取最优策略分割 s ,使剩下的字符 最少 。 示例 1: 输…
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表 记录字段中的所有单词,方便我们快速判断一个字符串是否在字典中。 接下来,我们定义 表示字符串 的前 个字符的最小额外字符数,初始时 $f[0] = 0$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的字符串 s 和一个单词字典 dictionary 。你需要将 s 分割成若干个 互不重叠 的子字符串,每个子字符串都在 dictionary 中出现过。s 中可能会有一些 额外的字符 不在任何子字符串中。
请你采取最优策略分割 s ,使剩下的字符 最少 。
示例 1:
输入:s = "leetscode", dictionary = ["leet","code","leetcode"] 输出:1 解释:将 s 分成两个子字符串:下标从 0 到 3 的 "leet" 和下标从 5 到 8 的 "code" 。只有 1 个字符没有使用(下标为 4),所以我们返回 1 。
示例 2:
输入:s = "sayhelloworld", dictionary = ["hello","world"] 输出:3 解释:将 s 分成两个子字符串:下标从 3 到 7 的 "hello" 和下标从 8 到 12 的 "world" 。下标为 0 ,1 和 2 的字符没有使用,所以我们返回 3 。
提示:
1 <= s.length <= 501 <= dictionary.length <= 501 <= dictionary[i].length <= 50dictionary[i]和s只包含小写英文字母。dictionary中的单词互不相同。
解题思路
方法一:哈希表 + 动态规划
我们可以用一个哈希表 记录字段中的所有单词,方便我们快速判断一个字符串是否在字典中。
接下来,我们定义 表示字符串 的前 个字符的最小额外字符数,初始时 。
当 时,第 个字符 可以作为一个额外字符,此时 ,如果在 中存在一个下标 ,使得 在哈希表 中,那么我们可以将 作为一个单词,此时 。
综上,我们可以得到状态转移方程:
其中 ,而 且 在哈希表 中。
最终答案为 。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度,而 是字典中所有单词的长度之和。
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
ss = set(dictionary)
n = len(s)
f = [0] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i - 1] + 1
for j in range(i):
if s[j:i] in ss and f[j] < f[i]:
f[i] = f[j]
return f[n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N^2 + M \cdot K) |
| 空间 | O(N + M \cdot K) |
面试官常问的追问
外企场景- question_mark
Can the candidate explain the reasoning behind the use of dynamic programming here?
- question_mark
Does the candidate demonstrate a good understanding of the pattern of breaking down a string into dictionary words?
- question_mark
Is the candidate able to optimize the solution by minimizing extra characters efficiently?
常见陷阱
外企场景- error
Failing to optimize the solution, leading to unnecessary extra characters left over.
- error
Overcomplicating the problem by not recognizing the value of hashing dictionary words for efficient lookups.
- error
Not managing dynamic programming states correctly, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
Handling a dictionary with very large numbers of words.
- arrow_right_alt
Optimizing the solution for longer strings with many possible splits.
- arrow_right_alt
Implementing the solution without relying on dynamic programming for a more brute force approach.