lintcode:Longest Substring with At Most K Distinct Characters

504 篇文章 0 订阅
66 篇文章 0 订阅
Medium Longest Substring with At Most K Distinct Characters 
26%
Accepted

Given a string s, find the length of the longest substring T that contains at most k distinct characters.

Example

For example, Given s = "eceba"k = 3,

T is "eceb" which its length is 4.

Challenge

O(n), n is the size of the string s.


class Solution {
public:
    /**
     * @param s : A string
     * @return : The length of the longest substring 
     *           that contains at most k distinct characters.
     */
     
    //ecebbbbdf
    //eebcaaad
     
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        // write your code here
        if (k<=0)
            return 0;
        
        
        if (s.size() < k)
            return 0;
            
        map<char, int> myMap;
        int curStart = 0;
        int curEnd = 0;
        int maxStart = 0;
        int maxEnd = 0;
        
        int idx = 0;
        bool found = false;
        
        for (int idx=0; idx< s.size(); idx++) 
        {
            if (myMap.count(s.at(idx)) == 0)
            {
                myMap[s.at(idx)] = 1;
                
                if (myMap.size() > k)
                {
                    if (curEnd-curStart > maxEnd-maxStart)
                    {
                        maxStart = curStart;
                        maxEnd   = curEnd;
                    }
                    
                    while (myMap.size() > k)
                    {
                        myMap[s.at(curStart)]--;
                        if (myMap[s.at(curStart)] == 0)
                        {
                            myMap.erase(s.at(curStart));
                        }
                        curStart++;
                    }
                }
            }
            else
            {
                myMap[s.at(idx)]++;
            }
            
            curEnd = idx;
        }
        
        if (curEnd-curStart > maxEnd-maxStart)
        {
            maxStart = curStart;
            maxEnd   = curEnd;
        }
        
        return maxEnd-maxStart+1;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值