题目:找出一个字符串中最长连续相邻子串,比如ababcabc,最长连续字串是abc。
分析:第一步,首先定义一个指针pStr定位于字串首部,再定义一个指针qStr指向pStr的下一个,然后qStr++找出与*pStr相同的字符;
第二步,如果找到*qStr==*pStr,则递增两个指针,并计算下相同字符的数目num和这段相同子字符串的index。
第三步,如果*qStr!=*pStr,则设置num=0。接着转向第一步...
第四步,定义一个maxNum和一个maxIndex,记录最长子字符串的长度和位置。如果一个新的num>maxNum,则maxNum=num,maxIndex=index。
#includeusing namespace std; void FindStr(char* str) { if(str == NULL) return; char* pStr = str; char* qStr = str+1; char* index = str; char* maxIndex = str; int num = 0; int maxNum = 0; while(*pStr != '\0') { while(*qStr != *pStr){ num = 0; qStr++; } while(*qStr == *pStr && *pStr !='\0' && *qStr !='\0') { num++; index = pStr; qStr++;//千万不要放在if(...)中 pStr++; } if(num>=1) index = index-num+1; if(num > maxNum){ maxNum = num; maxIndex = index; } // pStr++; qStr = pStr+1; } cout << "Result: "; for(int i=0;i