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.
====================================================================================
题目链接:https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/
题目大意:给定一个字符串s和一个整数k,找出每个字母个数都不小于k的最长子字符串长度。
思路:先找出字符串中个数小于k的字符,根据这些字符将原字符串拆分成多个子字符串,递归计算符合条件的最大子字符串长度。
具体实现:
1、建立一个映射表,从字符映射到个数。
2、用set将不符合条件的字符记录下来。
3、通过set中记录的字符将原字符串拆分成多个子字符串。
4、递归分别计算每个子字符串最大符合条件子串长度。
5、取所有子串计算结果最大值。
附上代码:
class Solution {
public:
int longestSubstring(string s, int k) {
int n = s.size() , ans = 0 ;
bool isValid = true ;//记录s是否满足条件
if ( k <= 1 )
return n ;
if ( n == 0 )
return 0 ;
map <char,int> m ;//建立映射表,字符映射到个数
for ( int i = 0 ; i < n ; i ++ )
m[s[i]] ++ ;
set <char> ss ;//记录不满足条件的字符
for ( map <char,int>::iterator it = m.begin() ; it != m.end() ; it ++ )
{
if ( it -> second < k )
{
isValid = false ;//s不满足条件
ss.insert ( it -> first ) ;
}
}
if ( isValid )//如果s满足条件则直接返回s的大小
return n ;
vector <string> v ;
string str = "" ;
for ( int i = 0 ; i < n ; i ++ )
{
if ( ss.find ( s[i] ) != ss.end() )//找到不符合要求的字符
{
if ( str != "" )
v.push_back ( str ) ;
str = "" ;
}
else //找不到不符合要求字符
str += s[i] ;
}
if ( str != "" )
v.push_back ( str ) ;
for ( int i = 0 ; i < v.size() ; i ++ )//找到最大值
ans = max ( ans , longestSubstring ( v[i] , k ) ) ;
return ans ;
}
};