LeetCode340 Longest Substring with At Most K Distinct Characters

This is a question needs pay for , I have no money to pay ,so just write some test case by myself.

If you read this blog , and you hava pay for the LeetCode ,and you have test my program , please tell me that wheather is works, thank you.

This idea is:We use double pointer and a count , and an array calls "locs" to  save the char last occur position.

if cnt>k,we need find the minimum position that a char occur. Here we can also use a map do this.

If you think why I use so ugly Englist to write this blog .Well ,Beacuse my computer is so slow if I use the Pinyin.Fuck the computer ,Fuck the Sougou.

Then , My Code:

#include <stdio.h>
#include <string.h>
#include <string>

using namespace std;

int getSub(string a,int k){
    int n = a.size();
    if(k>=n) return n;
    int cntChar = 0;
    int len = 0;
    int start = 0;
    int newStart=0;
    int locs[256];
    memset(locs,-1,sizeof(locs));
    for(int i=0;i<n;i++){
         newStart = start;
        if(locs[a[i]] == -1){cntChar++;}
        locs[a[i]] = i;
        if(cntChar<=k){len  = max(len,i-start+1);}
        else{
            for(int j=start+1;j<locs[a[start]];j++){
                newStart = min(locs[a[start]],locs[a[j]]);
            }
            locs[a[newStart]] = -1;
            cntChar --;
            start = newStart+1;
            len = max(len,i-start+1);
        }
    }
    return len;
}
int main()
{
    string a = "ecebbbbbcecba";
    int k = 2;
    int res = getSub(a,k);
    printf("%d\n",res);
    system("pause");
    return 0;
}

 

你可能感兴趣的:(LeetCode340 Longest Substring with At Most K Distinct Characters)