题目:
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.
Subscribe to see which companies asked this question
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
map<char,int> p;
vector<int> l(n);
for(int i = 0; i < n; i++)
{
if(i == 0)
l[i] = 0;
else
{
if(p.find(s[i]) != p.end())
{
l[i] = max(l[i-1], p[s[i]] + 1);
}
else
{
l[i] = l[i-1];
}
}
p[s[i]] = i;
}
int sum = 0;
for(int i = 0; i < n; i++)
{
sum = max(sum, i - l[i] + 1);
}
return sum;
}
};