Description:
Given a string, find the length of the longest substring without repeating characters.
Example1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example3:
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.空字符串
2.窗口滑动方法
int lengthOfLongestSubstring(char* s) {
if (s == "") return 0; //?????
int max = 0,i=0,j=0,k,flag=0,max_tmp=0;
while (s[j] != '\0')
{
for (k = j-1; k >= i; k--)
{
if (s[k] == s[j])
{
flag = 1;
break;
}
} //有重复flag=1||循环满了flag=0
if (flag == 0) //循环满了 更新当前最大值
max_tmp++;
else //字符有重复,更新i值,窗口滑动,更新窗口长度 ;更新flag
{
i = k + 1;
max_tmp = j - i + 1;
flag = 0;
}
if (max_tmp > max) max = max_tmp;
j++;
}
return max;
}
运行结果: