zoukankan      html  css  js  c++  java
  • 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
    ",res);
        system("pause");
        return 0;
    }
  • 相关阅读:
    装饰器
    异常处理与断言
    例子:对象构造函数指定类型传入参数(描述符与装饰器的应用)
    Python的描述符
    全新开始fighting
    函数相关知识
    集合的介绍以及简单方法
    列表,元组,字典类的常见简单方法
    Python简单字符串函数介绍
    聚合函数及分组查询及F&Q
  • 原文地址:https://www.cnblogs.com/yueyanglou/p/5395684.html
Copyright © 2011-2022 走看看