Given a string, find the length of the longest substring without repeating characters. 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.
定义 L[ i ] =s[m...i],表示无重复字符的最长子串,且以 s[m] 开始,以s[i]结束。 同时我们对 [m...i]维护一个 hashmap,结构为<char ,int >,键为字符,对应的值是出现在原始字符串s中的位置。当我们计算到 s[i+1]时,
1.如果s[i+1]没有出现在s[m...i]中(可以用hashmap来查找),则将s[i+1]添加进去,此时L[i+1]= s[m...i i+1]。
2.如果s[i+1]出现在s[m...i]中, 假设其位置为j,则 L[i+1]=s[j+1...i+1]。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> hash;
int maxlen = 0;
int index = 0;
for (int i = 0; i < s.size(); i++)
{
if(hash.find(s[i]) != hash.end())
{
index = hash[s[i]];
for (auto it = hash.begin(); it != hash.end();)
{
if (it->second <= index)
{
it = hash.erase(it);
}else{
it++;
}
}
}
hash[s[i]] = i;
if (maxlen < hash.size()) maxlen = hash.size();
}
return maxlen;
}
};