2370. Longest Ideal Subsequence
On This Page
class Solution:
def longestIdealString(self, s: str, k: int) -> int:
n = len(s)
res = 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)