- 3, longest substring without rep
- #3 Longest Substring Without Rep
- #3 Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
采用滑动窗口算法(Slide Window Algorithm)。
设下标 l 和 r, 把左开右闭 [l, r) 想象成一个窗口。
当s[r] 和窗口内字符重复时, 则 l 向右滑动,缩小窗口。
当s[r] 和窗口内字符不重复时,则 r 向右滑动,扩大窗口,此时窗口内的字符串一个无重复子字符串。
每次比较s[j] 和[i,j) ,i默认从零开始,如果某次发现 s[n] == s[j], i<=n<j , i就更新为n+1, 然后计算n+1到j的长度(j-(n+1)+1),然后和目前最大max比较 ,保存最大max.
#define max(a,b) (a>b?a:b)
int lengthOfLongestSubstring(char* s) {
int i = 0;
int j = 1;
int len = strlen(s);
if(len == 0)
return 0;
int maximum = 1;
int duplicate = 0;
int index = -1;
for(int j = 1; j < len; j++){
//if new s[k] duplicate with anyone in s[0, k-1] or s[i,j]
//if yes(same as a[m] (i=<m<=j), i = m++), j++; or only j++;
for(int n = j-1; n >= i ; n--){
if(s[j] == s[n]){
index = n;
duplicate = 1;
break;
}
}
if(duplicate){
//
duplicate = 0;
i = index+1;
}
maximum = max(maximum, j-i+1);
}
return maximum;
}
网友评论