leetcode 395. 至少有K个重复字符的最长子串

这道题类似于leetcode 394,我用的是递归的思想。
先建立一个辅助容器,unordered_map<char,int>work,用来存储本段字符串的每一个字符的出现次数。然后如果存在work[i]<k,则从i处分割字符串,对分割出来的子字符串进行递归。这么做的原因是如果确定该字符出现的次数小于k,那么最长的满足要求的子串必定不能含有该字符。
另外的就是注意设置好递归的边界条件,考虑好k<=0,s为空的情况。

class Solution {
public:
    int longestSubstring(string s, int k) {
        if(k<=0)
            return s.size();
        if(s.size()<k)
            return 0;
        unordered_map<char,int>work;
        for(auto i:s)
            work[i]++;
        bool flag=true;
        for(auto i:work){
            if(i.second<k)
                flag=false;
        }
        if(flag==true)
            return s.size();
        int pre=0;
        int maxLen=0;
        int i=0;
        for(;i<s.size();++i){
            if(work[s[i]]<k){
                maxLen=max(maxLen,longestSubstring(s.substr(pre,i-pre),k));
                pre=i+1;
            }
        }
        maxLen=max(maxLen,longestSubstring(s.substr(pre,i-pre),k));
        return maxLen;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值