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.
解题思路是建立一个映射表,检查两个重复字符之间的间隔长度。
int lengthOfLongestSubstring(string str)
{
// create table to store all ASCII
vector<int> vecTable(256,-1);
int nMaxLen = -1;
int nStart = -1;
for (int i = 0; i < str.length(); ++i)
{
// Target character's position is after previous location
if (vecTable[str[i]] > nStart)
{
nStart = vecTable[str[i]];
}
// Update target character's position;
vecTable[str[i]] = i;
nMaxLen = max(nMaxLen, i - nStart);
} return nMaxLen;
}