LeetCode Longest Substring with At Least K Repeating Characters

LeetCode Longest Substring with At Least K Repeating Characters 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.

给定一个字符串s和数字k,求s的子串中每个字母都至少出现k次的最长子串的长度。 因为题目规定字符串中只有26个小写字母,所以可以用一个int来Hash某个子串,如果某字母出现次数小于k次,则对应位为1,否则对应位为0。最后,在遍历的过程中,判断子串的Hash值是否等于0,如果是则该子串满足要求,更新最大长度。 完整代码如下: [cpp] class Solution { public: int longestSubstring(string s, int k) { int maxLen = 0; for (int i = 0; i < s.size(); ++i) { vector<int> mask(26, 0); int j = i, flag = 0; while (j < s.size()) { ++mask[s[j] – ‘a’]; if (mask[s[j] – ‘a’] < k)flag |= (1 << (s[j] – ‘a’)); else flag &= (~(1 << (s[j] – ‘a’))); if (flag == 0)maxLen = max(maxLen, j – i + 1); ++j; } } return maxLen; } }; [/cpp] 本代码提交AC,用时196MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *