最长理想子序列
难度:
标签:
题目描述
代码结果
运行时间: 289 ms, 内存: 16.4 MB
// Problem description:
// Given a string s and an integer k, find the length of the longest ideal subsequence in s.
// A subsequence is ideal if the absolute difference between the positions of every two adjacent characters in the subsequence is less than or equal to k.
import java.util.stream.IntStream;
public class LongestIdealSubsequenceStream {
public int longestIdealString(String s, int k) {
int[] dp = new int[26];
s.chars().forEach(c -> {
int pos = c - 'a';
int maxLength = IntStream.rangeClosed(Math.max(0, pos - k), Math.min(25, pos + k))
.map(i -> dp[i])
.max()
.orElse(0);
dp[pos] = maxLength + 1;
});
return IntStream.of(dp).max().orElse(0);
}
}
解释
方法:
该题解采用动态规划的方式来求解最长理想子序列的长度。dp数组的每个元素dp[ord(c)]表示以字符c结尾的最长理想子序列的长度。遍历给定字符串s中的每个字符c,计算以该字符结尾的最长理想子序列长度,方法是查看在字符c的ASCII码基础上前后k范围内的所有字符所记录的最长子序列长度,找到最大值后加1即为以字符c结尾的最长理想子序列的长度。最后,返回dp数组中的最大值即可。
时间复杂度:
O(n*k)
空间复杂度:
O(1)
代码细节讲解
🦆
在动态规划解法中,dp数组为何选择长度为128,这是否与ASCII码的范围有关?
▷🦆
在计算dp[ord_c]时,为什么是取前后k个ASCII范围内的dp值的最大值加1?这样做的主要逻辑是什么?
▷🦆
该算法在处理字符时是否考虑了所有可能的字符(包括非小写字母)?如果是,这样做是否有潜在的问题或优点?
▷🦆
在实际代码实现中,为什么选择了range 'ord_c - k: ord_c + k + 1',这里的边界处理(比如当ord_c - k < 0或ord_c + k > 127时)是如何确保不会出现错误的?
▷