题目:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
参考思路:从左向右扫描,扫描一个字母记录为True,同时right++,一旦遇到扫描过的字母,则将该字母记为false同时将lft++;(即跳过该字母,以他的后面第一个元素作为起点,从刚才的right继续往后扫描,找到最大的不重复子串)
leetcode给的参考代码。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
if (n<2) return n;
int lft = 0, rgt = 0, maxlen = 0;
bool sign[128] = { false };
while (rgt<n)
{
if (sign[(int)s[rgt]] == false)
{
sign[(int)s[rgt]] = true;
rgt++;
if (maxlen<rgt - lft)
maxlen = rgt - lft;
continue;
}
sign[(int)s[lft]] = false;//跳过这个字母扫描,假设这个字母没有出现过
lft++;
}
return maxlen;
}
};