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.
这个题目想了挺久的,最后参考了别人的解法。用两个指针,一个指向当前子串的头,一个指向尾,尾指针不断往后扫描,当有字符前面出现过了,记录当前子串长度和最优解的比较结果。然后头指针不断往后扫描,直到扫描到一个字符和尾指针相同,则尾指针继续扫描,当尾指针到达字符串结尾,算法结束。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
bool exist[256] = {false};
int maxLen = 0;
int i = 0, j = 0;
int n = s.size();
while (j < n)
{
if (exist[s[j]])
{
maxLen = max(maxLen, j - i);
for (;s[i] != s[j]; i++)
exist[s[i]] = false;
i++;
j++;
}
else
{
exist[s[j]] = true;
j++;
}
}
maxLen = max(maxLen, n - i);
return maxLen;
}
};