Longest Substring Without Repeating Characters
问题描述
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(string s)
{
if (s == "")
return 0;
if (s.size() == 1)
return 1;
int maxLen = 1;
int start = 0;
for (int i = 1; i < s.size(); i++)
{
int len = 1;
for (int j = start; j < i; j++)
{
if (s[i] == s[j])
{
start = j+1;
break;
}
len++;
if (len>maxLen)
maxLen = len;
}
}
return maxLen;
}
思路:
(1)从下标为1处开始,遍历string
(2)(1)中的下标,可以看做是子串的目标结束位置的后一位置
(3)刚开始,令start=0,标识子串的开始位置
(4)遍历(1)-(3)中的子串,如果子串中不存在和(1)中相同的点,则将(1)中的字符加入子串,长度+1
(5)否则,则新的start的位置设置为与(1)中字符相同的位置的后一位置
(6)继续上述过程
**注意:**开始的长度要设置为1