首页 > 代码库 > 一道题目
一道题目
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);}
一道题目
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。