[leetcode]395. Longest Substring with At Least K Repeating Characters

本文介绍了一种解决LeetCode上最长子串问题的方法,该问题要求在给定字符串中找到每个字符至少重复k次的最长子串。通过遍历字符串并分割不符合条件的字符来递归求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/#/description

 

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.

 

 

思路:先遍历整个string,并记录每个不同的character的出现次数。如果所有character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;如果有character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次递归,找到最大的返回值即可。

 

class Solution{
public:
    int longestSubstring(string s,int k)
    {
        vector<int> bucket(26,0);
        for(auto c:s)
            bucket[c-'a']++;
        char delim=NULL;
        for(int i=0;i<26;i++)
        {
            if(bucket[i]>0 && bucket[i]<k)
            {
                delim=(char)(i+'a');
            }
        }
        if(delim==NULL)
            return (int)s.length();
        vector<string> res;
        int maxlen=0;
        stringstream ss(s);
        string g;
        while(getline(ss,g,delim))
        {
            res.push_back(g);
        }
        for(auto str:res)
        {
            maxlen=max(maxlen,longestSubstring(str,k));
        }
        return maxlen;
    }
};

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值