zoukankan      html  css  js  c++  java
  • 一道题目

    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);
    }
  • 相关阅读:
    [ARC117F]Gateau
    [ARC117D]Miracle Tree
    [loj3504]支配
    [gym102511K]Traffic Blights
    [loj3501]图函数
    [loj3503]滚榜
    [loj3500]矩阵游戏
    [loj2135]幻想乡战略游戏
    [cf720D]Slalom
    [cf1349E]Slime and Hats
  • 原文地址:https://www.cnblogs.com/whyandinside/p/3953415.html
Copyright © 2011-2022 走看看