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.
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
class Solution{
public:
int lengthOfLongestSubstring(string s){
int length=s.size();
map<char,int> charmap;
int maxLen=0,lastindex=-1;
for(int i=0;i<length;i++){
if(charmap.find(s[i])!=charmap.end() && lastindex<charmap[s[i]])//s[i] is a char
lastindex=charmap[s[i]];
maxLen=max(maxLen,i-lastindex);
charmap[s[i]]=i;
}
return maxLen;
}
};
int main(){
Solution sol;
string s="abcabcccsddd";
int temp=sol.lengthOfLongestSubstring(s);
cout<<temp<<endl;
return 1;
}