[LeetCode] Find Maximum Number of Non Intersecting Substrings

3557. Find Maximum Number of Non Intersecting Substrings

You are given a string word.

Return the maximum number of non-intersecting substrings of word that are at least four characters long and start and end with the same letter.

A substring is a contiguous non-empty sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int maxSubstrings(string word) {
int n = word.size();
vector<int> dp(n), meet(26, -1);
for(int i = 0; i < n; i++) {
if(i) dp[i] = dp[i-1];
if(i >= 3) meet[word[i-3]-'a'] = i - 3;
if(meet[word[i]-'a'] != -1) {
dp[i] = max(dp[i], 1 + (meet[word[i]-'a'] ? dp[meet[word[i]-'a'] - 1] : 0));
}
}
return dp.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/05/25/PS/LeetCode/find-maximum-number-of-non-intersecting-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.