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) {
int freq[256] = {0};
int l = 0,r = -1;
int res = 0;
while (l < s.size())
{
if (r+1 < s.size() && freq[s[r+1]] == 0) freq[s[++r]] ++;
else freq[s[l++]] --;
res = max(res , r-l+1);
}
return res;
}
};