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.
最高赞答案form discuss
思路:一个dict做字典,记录当前字符s[i]上一次出现的下标
256是因为ascii码。最多就256个字符。
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1); //256长的vector,初始化为-1(dict的索引是字符)
int maxLen = 0, start = -1;//起点初始化为-1
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start) //如果当前字母在前面出现过的位置比当前记录的start靠后
start = dict[s[i]];//说明有重复字母了,更新start
dict[s[i]] = i;//把当前i赋给字母对应的值
maxLen = max(maxLen, i - start);
}
return maxLen;
}