[LeetCode] Longest Ideal Subsequence

2370. Longest Ideal Subsequence

You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:

  • t is a subsequence of the string s.
  • The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.

Return the length of the longest ideal string.

A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of ‘a’ and ‘z’ is 25, not 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
vector<vector<int>> mp;
int dp[101010];
int helper(string& s, int p, int k) {
if(dp[p] != -1) return dp[p];
int& res = dp[p] = 1;
for(int ch = max((s[p] - k - 'a'),0); ch <= min((s[p] + k - 'a'),25); ch++) {
if(mp[ch].empty()) continue;
auto lb = lower_bound(begin(mp[ch]), end(mp[ch]), p + 1);
if(lb == end(mp[ch])) continue;

res = max(res, 1 + helper(s,*lb,k));
}
return res;
}
public:
int longestIdealString(string s, int k) {
memset(dp,-1,sizeof dp);
mp = vector<vector<int>>(26);
for(int i = 0; i < s.length(); i++) {
mp[s[i]-'a'].push_back(i);
}
int res = 0;
for(int ch = 0; ch < 26; ch++) {
if(mp[ch].empty()) continue;
res = max(res, helper(s,mp[ch][0], k));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/07/PS/LeetCode/longest-ideal-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.