Skip to content

Commit 74cc3bf

Browse files
committed
[feat ]: leetcode 2370
Signed-off-by: Bo-Wei Chen(BWbwchen) <tim.chenbw@gmail.com>
1 parent a9f12b6 commit 74cc3bf

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
inline bool valid(char a, char b, int k) {
4+
return abs(a - b) <= k;
5+
}
6+
int longestIdealString(string s, int k) {
7+
int n = s.size();
8+
vector<int> dp(26, 0); // a ~ z
9+
10+
for (auto c : s) {
11+
int tmp = std::numeric_limits<int>::min();
12+
for (char j = 'a'; j <= 'z'; ++j) {
13+
// dp[c] = max_j(dp[j]) + 1, where valid(j, c, k) == true
14+
if (valid(j, c, k))
15+
tmp = max(tmp, dp[j-'a']);
16+
}
17+
// Why use tmp? Because we can not update the dp[c-'a'] and compare it simultaneously.
18+
dp[c-'a'] = max(dp[c-'a'], tmp + 1);
19+
}
20+
return *max_element(dp.begin(), dp.end());
21+
}
22+
};

0 commit comments

Comments
 (0)