题目:
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.
解答:
int lengthOfLongestSubstring(char* s) {
int num[128]; //用于记录26个英文字母最近一次出现的位置,如果未出现则为-1
int flag = 0; //用于标记遍历过程中子串的起始位置
int maxlength = 0; //用于记录当前最大子串的长度
int i = 0;
int temp;
//初始化num的值为-1
memset(num,-1,128*sizeof(int));
for (i = 0; i<strlen(s); i++)
{
temp = num[s[i]];
num[s[i]]=i;
if (temp>=flag) //该处字母在之前出现过
{
maxlength =maxlength>(i - flag)? maxlength:(i - flag);
flag = temp + 1;
}
}
maxlength =maxlength>(i - flag)? maxlength:(i - flag);
return maxlength;
}