Given a string, find the length of the longest substring without repeating characters.
Example
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
.
Challenge
O(n) time
class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
int lengthOfLongestSubstring(string s) {
// write your code here
vector<int> dp(s.size()+1);
map<int, int> posMap;
dp[0] = 0;
int retMax = 0;
for (int i=0; i<s.size(); i++)
{
if (posMap.count(s.at(i)) == 0)
{
dp[i+1] = dp[i]+1;
}
else
{
dp[i+1] = min(i-posMap[s.at(i)], dp[i]+1);
}
posMap[s.at(i)] = i;
retMax = max(retMax, dp[i+1]);
}
return retMax;
}
};