2370. Longest Ideal Subsequence

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 2370

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)