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次的字符,从这个字符分成左右两个子串,递归判断,直至找到最大值
可能是test case 更新了,所以递归做法会超时,于是后来又看了一个做法,
由于字母只有26个,而整型mask有32位,足够用了,每一位代表一个字母,如果为1,表示该字母不够k次,如果为0就表示已经出现了k次,这种思路真是太聪明了。我们遍历字符串,对于每一个字符,我们都将其视为起点,然后遍历到末尾,我们增加哈希表中字母的出现次数,如果其小于k,我们将mask的对应位改为1,如果大于等于k,将mask对应位改为0。然后看mask是否为0,是的话就更新res结果,然后把当前满足要求的子字符串的起始位置j保存到max_idx中,等内层循环结束后,将外层循环变量i赋值为max_idx+1,继续循环直至结束,
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
int longestSubstring(string s, int k)
{
if (k <= 0)
return s.length();
if (s.length() <= 0 || k > s.length())
return 0;
int i = 0, maxLen = 0;
while (i + k <= s.length())
{
int mask = 0, index = i;;
vector<int> count(26, 0);
for (int j = i; j < s.length(); j++)
{
count[s[j] - 'a']++;
if (count[s[j] - 'a'] < k)
mask |= (1 << (s[j] - 'a'));
else
mask &= (~(1 << (s[j] - 'a')));
if (mask == 0)
{
maxLen = max(maxLen, j - i + 1);
index = j;
}
}
i = index + 1;
}
return maxLen;
}
int longestSubstringByDFS(string s, int k)
{
if (k <= 0)
return s.length();
else if (s.length() <= 0 || k > s.length())
return 0;
else
{
map<char, int> mmp;
for (char a : s)
{
if (mmp.find(a) == mmp.end())
mmp[a] = 1;
else
mmp[a] += 1;
}
int index = 0;
for (index = 0; index<s.length(); index++)
{
if (mmp[s[index]] < k)
break;
}
if (index == s.length())
return s.length();
else
{
string left = s.substr(0, index);
string right = s.substr(index + 1);
int a = longestSubstring(left, k);
int b = longestSubstring(right, k);
return max(a, b);
}
}
}
};