395. Longest Substring with At Least K Repeating Characters,longestrepeating
分享于 点击 4853 次 点评:258
395. Longest Substring with At Least K Repeating Characters,longestrepeating
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
这题如果逐一查找的话,操作起来不太方便,这题最方便的做法就是递归了。建立一个数组来统计每个字母出现的次数,对于出现次数少于K次的,我们把它们当做间隔,从而把原数列分为几段,要找的满足重复的最长的子序列一定在这几段其中。对于分开的每段,又是一个同样性质的子问题。如果一段中没有小于K的间隔,那么直接返回这一段的长度,更新最大长度。
int longestSubstring(string s, int k) {
return helper(s, k, 0, s.size() - 1);
}
int helper(string s, int k, int left, int right) {
int len = right - left + 1;
if (len <= 0) return 0;
int i, j;
int maxlen = 0;
vector<int> count(26, 0);
for (i = left; i <= right; i++) {
count[s[i] - 'a']++;
}
for (i = left, j = left; i <= right; i++) {
if (count[s[i] - 'a'] < k) {
maxlen = max(maxlen, helper(s, k, j, i - 1));
j = i + 1;
}
}
if (j == left) return len;
else return max(maxlen, helper(s, k, j, i - 1));
}
注意一下,最后一句的处理:
else return max(maxlen, helper(s, k, j, i - 1));
如果在原数列中出现了间隔,那么最后一个间隔到right之间这一段是没有参与计数,这个很容易被忽视。leetcode有测试用例特意测了这一点。
相关文章
- 暂无相关文章
用户点评