cpp solution using sliding window approach


  • 0
    G

    class Solution {
    public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {

        if(!k || !s.length())
            return 0;
            
            
        int distinct = 0, maxi = 0, str = 0 , j = 0;
        vector<int> ar(256,0);
        
        for(int i = 0 ; i < s.length() ; ){
            
            
            if(ar[s[i]] == 0){
                distinct++;
            }
            
            ar[s[i]]++;
            i++;
    
            while(distinct > k){
                if(--ar[s[j++]] == 0)
                    distinct--;
            }
            
            //cout<<i<<"  "<<i<<" "<<j<<endl;
    
            maxi = max(maxi,i-j);
        }
        
        return maxi;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.