首页 > 代码库 > 一道题目

一道题目

given a string ,return the longest substring that contains at most two characters.

extern "C" char *SubStringWithAtMost2Chars(char * pStr, int len){    if(len <= 2)        return pStr;    char ch1, ch2;    int ch1Index= -1, ch1Cnt = 0, ch2Cnt = 0;    char lastCh1 = 0, lastCh2 = 0;    int lastCh1Index = -1,lastCh2Index = -1, lastCh1Cnt = 0, lastCh2Cnt = 0;    for(int i = 0;i< len; i++)    {        if(lastCh1Cnt == 0)        {            lastCh1 = pStr[i];            lastCh1Index = i;            lastCh1Cnt ++;        }        else        {            if(lastCh2Cnt == 0)            {                if(pStr[i] == lastCh1)                {                    lastCh1Cnt++;                }                else                {                    lastCh2 = pStr[i];                    lastCh2Cnt++;                    lastCh2Index = i;                }            }            else            {                if(pStr[i] == lastCh2)                {                    lastCh2Cnt++;                }                else                {                    if((lastCh1Cnt + lastCh2Cnt) > (ch1Cnt + ch2Cnt))                    {                        ch1 = lastCh1;                        ch2 = lastCh2;                        ch1Index = lastCh1Index;                        ch1Cnt = lastCh1Cnt;                        ch2Cnt = lastCh2Cnt;                    }                    lastCh1 = lastCh2;                    lastCh1Index = lastCh2Index;                    lastCh1Cnt = lastCh2Cnt;                    //below is missed                    lastCh2Cnt = 1;                    lastCh2Index = i;                    lastCh2 = pStr[i];                }            }        }    }    if((lastCh1Cnt + lastCh2Cnt) > (ch1Cnt + ch2Cnt))    {        ch1 = lastCh1;        ch2 = lastCh2;        ch1Index = lastCh1Index;        ch1Cnt = lastCh1Cnt; //missed        ch2Cnt = lastCh2Cnt; //missed    }    char *pSubStr = (char *) malloc(ch1Cnt + ch2Cnt + 1);    memset(pSubStr, 0, ch1Cnt + ch2Cnt + 1);    memcpy(pSubStr,pStr+ ch1Index, ch1Cnt + ch2Cnt);}

 

一道题目