增强题 : 九章算法 | Google面试题9 : 最多有k个不同字符的最长子字符串(分享自知乎网)点击打开链接
普通题如下:
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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxlen = 0;
unordered_map <char, int > map;
int i = 0 ;
int j = -1;
char c = 0;
for (int i = 0; i < s.length(); i++)
{
while (j < (int)s.length()-1)
{
j++;
c = s[j];
if (map.find(c) != map.end())
{
j--;
break;
}
else
{
map.insert(pair <char, int >(c, 1));
}
}
maxlen = maxlen > j - i +1? maxlen : j - i +1 ;
c = s[i];
if (map.find(c) != map.end())
{
map.erase(c);
}
}
return maxlen;
}
};