问题描述
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.
分析
“dict”用于跟踪每次读取的输入字符串中的字符。 start表示子串起始位置的位置。 在开始时,它将“dict”中的所有值初始化为-1。 然后在for循环中,它扫描字符串中的每个字符。 如果“dict”的值大于“start”,则意味着它已经在子字符串中。 您应该将子串的开始位置更改为重复位置并开始新的计数。 “maxLen”记录你到目前为止的子串的最大长度。
算法(C++)
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}