Longest Substring Without Repeating Characters
Description
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
**My Terrible Solution**
/*
**对字符串操作不太熟悉
*/
int lengthOfLongestSubstring(char* s) {
int maxLength=0;
if(s[1]=='\0'){
return 1;
}
for(int i=0;s[i]!='\0';i++){
int length=0;
for(int j=i;s[j]!='\0';j++){
int flag=1;
for(int k=i;k<j;k++){
if(s[j]==s[k]){
flag=0;
break;
}
}
if(flag==0){
if(maxLength<length){
maxLength=length;
}
length=0;
break;
}
length++;
}
if(maxLength<length){
maxLength=length;
}
}
return maxLength;
}
Excellent Solution
int lengthOfLongestSubstring(char* s) {
if(s == NULL || strlen(s) == 0)
return 0;
char* p = s;
int len = strlen(s) + 1;
char* subString = (char*)malloc(len * sizeof(char));
memset(subString,0,len);
// [a , b ,c , d ,v , d ,x , y ,d ,z]
// | | |
//first now end
int pFirstIndex = 0; //找到一个相同字符时,要求的nowIndex那个字符的长度,是前边加后边
int pNowIndex = 0; //p移动到了多少位置
int pEndIndex = 0;//第二个找到的字符的位置
int i = 0; //子字符串下标
int max = 0;//找到的重复的字符串的长度,作为返回值
while(pEndIndex < len-1){//遍历数组
for(int j= pFirstIndex; j < i; j++){
if(subString[j] == p[pEndIndex]){
//if(pFirstIndex == 0)
pNowIndex = j;
//printf("f=%d,n=%d,e=%d\n",pFirstIndex,pNowIndex,pEndIndex);
if((pNowIndex - pFirstIndex) + (pEndIndex - pNowIndex) > max)
max = (pNowIndex - pFirstIndex) + (pEndIndex - pNowIndex);
pFirstIndex = pNowIndex + 1;
//printf("get max = %d,f=%d\n",max,pFirstIndex);
}
}
subString[i++] = p[pEndIndex++];
}
//printf("e=%d,f=%d\n",pEndIndex,pFirstIndex);
if((pEndIndex - pFirstIndex) > max){
max = (pEndIndex - pFirstIndex); //最后那一段的数据的长度,因没有找到一个一样的,所以是直接就是那个长度
//printf("max2 = %d\n",max);
}
return max;
}