# LeetCode--Longest Substring Without Repeating Characters

#Longest Substring Without Repeating Characters
###题目
Given a string, find the length of the longest substring without repeating characters.
####Example

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", which the length is 3.


####Example

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.


####Example

Input: "pwwkew"
Output: 3
Explanation: 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.


###分析

1. 当字符与前面的某个字符重复的时候，这是个重新遍历的临界点，这时选择的遍历起点是重复字符的前面一个的下标，这样可以减少遍历次数。
###源码
int lengthOfLongestSubstring(char* s) {
int len = strlen(s);
int *count = (int*)malloc(256*sizeof(int));
memset(count,0,256*sizeof(int));
int *last_seen =  (int*)malloc(256*sizeof(int));
memset(last_seen,0,256*sizeof(int));
int max = 0;
int tag = 0;
for(int i = 0; i < len; i++) {
count[s[i]]++;
if(count[s[i]] > 1) {
if(max < tag) {
max = tag;
}
tag = 0;
memset(count,0,256*sizeof(int));
i = last_seen[s[i]];
memset(last_seen,0,256*sizeof(int));
continue;
} else {
tag++;
last_seen[s[i]] = i;
if(max < tag) {
max = tag;
}
}
}
free(count);
free(last_seen);
return max;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120