LeetCode 题解工作台
最长理想子序列
给你一个由小写字母组成的字符串 s ,和一个整数 k 。如果满足下述条件,则可以将字符串 t 视作是 理想字符串 : t 是字符串 s 的一个子序列。 t 中每两个 相邻 字母在字母表中位次的绝对差值小于或等于 k 。 返回 最长 理想字符串的长度。 字符串的子序列同样是一个字符串,并且子序列还满足…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
设 表示以字符 结尾的最长理想子序列的长度,利用哈希表 记录每个字符最新出现的位置。初始时 , 。 在 范围内的每个字符 ,获取它所有前一个合法字符的位置 ,那么 $dp[i]=max(dp[i], dp[j]+1)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个由小写字母组成的字符串 s ,和一个整数 k 。如果满足下述条件,则可以将字符串 t 视作是 理想字符串 :
t是字符串s的一个子序列。t中每两个 相邻 字母在字母表中位次的绝对差值小于或等于k。
返回 最长 理想字符串的长度。
字符串的子序列同样是一个字符串,并且子序列还满足:可以经由其他字符串删除某些字符(也可以不删除)但不改变剩余字符的顺序得到。
注意:字母表顺序不会循环。例如,'a' 和 'z' 在字母表中位次的绝对差值是 25 ,而不是 1 。
示例 1:
输入:s = "acfgbd", k = 2 输出:4 解释:最长理想字符串是 "acbd" 。该字符串长度为 4 ,所以返回 4 。 注意 "acfgbd" 不是理想字符串,因为 'c' 和 'f' 的字母表位次差值为 3 。
示例 2:
输入:s = "abcd", k = 3 输出:4 解释:最长理想字符串是 "abcd" ,该字符串长度为 4 ,所以返回 4 。
提示:
1 <= s.length <= 1050 <= k <= 25s由小写英文字母组成
解题思路
方法一:动态规划
设 表示以字符 结尾的最长理想子序列的长度,利用哈希表 记录每个字符最新出现的位置。初始时 , 。
在 范围内的每个字符 ,获取它所有前一个合法字符的位置 ,那么 。
答案为 中的最大值。
时间复杂度 ,空间复杂度 。
class Solution:
def longestIdealString(self, s: str, k: int) -> int:
n = len(s)
ans = 1
dp = [1] * n
d = {s[0]: 0}
for i in range(1, n):
a = ord(s[i])
for b in ascii_lowercase:
if abs(a - ord(b)) > k:
continue
if b in d:
dp[i] = max(dp[i], dp[d[b]] + 1)
d[s[i]] = i
return max(dp)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(NL) |
| 空间 | O(L) |
面试官常问的追问
外企场景- question_mark
The candidate correctly applies dynamic programming to solve the problem by defining an optimal state transition.
- question_mark
The candidate uses a hash map efficiently to store and retrieve subsequence lengths, reducing time complexity.
- question_mark
The candidate demonstrates a clear understanding of subsequence problems, especially the constraints defined by the alphabetic difference k.
常见陷阱
外企场景- error
Failing to optimize the solution by using a hash map can lead to O(N^2) time complexity, which is inefficient for large strings.
- error
Not correctly tracking the transitions between subsequences may result in incorrect or suboptimal solutions.
- error
The candidate might not consider edge cases such as the minimum or maximum values of k, or strings with a single character.
进阶变体
外企场景- arrow_right_alt
Consider variants where the string contains uppercase letters, expanding the alphabetic range.
- arrow_right_alt
Modify the problem to allow only a fixed number of deletions, adding a layer of complexity.
- arrow_right_alt
Test the solution with varying k values to examine how it handles different constraints in the problem.