上次面试的时候遇到了这个题,当时写的算比较完整了,这里用代码实现一下。
在循环条件判断的时候,竟然犯了指针没有解引用去判断是否equal NULL的低级错误,想必是这两天发烧头昏了。。。
每天写一点代码,每天进步一点点。加油~
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
bool contains( char *str, char *value, int num) {
if (*str == NULL || *value == NULL)
{
printf("please check the parameters\n");
return true;
}
for (;num > 0; ++str, --num) {
if ((*str) == (*value))
return true;
}
return false;
}
void max_substring(char *dest, char *&pret, int &count) {
pret = NULL;
count = 0;
char *pStart = dest, *pEnd, *pCurrent;
int tmpCount = 0;
while(*pStart != NULL) {
pCurrent = pStart;
pEnd = pCurrent + 1;
tmpCount = 1;
while(*pEnd != NULL && !contains(pCurrent, pEnd, tmpCount)) {
++pEnd;
++tmpCount;
}
if (tmpCount > count ) {
count = tmpCount;
pret = pCurrent;
}
if (*pEnd == NULL) return;
++pStart;
}
}
int main() {
char tom[] = "hello world";
char *tmpj;
int count;
printf("原始字符串是%s\n函数功能是求它最大的非重复子串\n",tom);
max_substring(tom, tmpj, count);
char result[sizeof(tom)];
strncpy(result, tmpj, count);
result[count] = NULL;
printf("count is %d, and the string is %s\n", count, result);
system("pause");
return 0;
}