题为:求最大长度的子串,要求不能有重复字符
首先想到的是暴力解决方法,循环创建每个子串,并记录长度,同时确认是否有重复字符,如下:
int lengthOfLongestSubstring(char* s)
{int maxLen = 0;int i = 0, j = 0, len = 0; char *p = s, *res = s;len = strlen(s); if (len <= 1)return len;char *buf = malloc(len + 1);if (buf == NULL){return -1;}while(*res != '\0'){for (i = 1; i <= strlen(res); i ++){memset(buf, 0, len+1); strncpy(buf, res, i);//printf("buf=[%s]\n", buf);p = buf;if (NULL != strstr(s, p)){//printf("found p=%s, len=%d\n", p, strlen(buf));int goon = 0;for (j = 0; j < strlen(p); j ++){int k = 0;for (k = j + 1; k < strlen(p); k ++){if (p[j] == p[k]){goon = 1;goto goon;}}}goon:if (goon){continue; } if (maxLen < strlen(p)){maxLen = strlen(p); }}}res ++; } free(buf);return maxLen;
}
网上有多个对这种问题的解决方法,C语言中没有现成的HASH/MAP的API,但是本质思想是一样的,对于这些字符使用其ASCII码进行HASH的对应,
也就是说256个字符类型完全可以在一个数组中对应,数组的下标表示字符的ASCII码,数组元素的值表示对应字符的位置,这样不同的字符的位置都不同,
当遇到相同字符出现时,则说明前面字符为不重复字符串,计算前后出现的距离长度,逐一轮询至末尾:
int lengthOfLongestSubstring_opt(char*s)
{int lenOfString = strlen(s);int i = 0, max = 0, end = 0;if (lenOfString == 0){return 0;}else if (lenOfString == 1){return 1;}int location[256] , index = -1;; memset(location, 0xff, sizeof(location)); for (i = 0; i < lenOfString; i ++){if (location[s[i]] > index) { index = location[s[i]];} if (i - index > max) { max = i - index; } location[s[i]] = i; }return max ;
}