Use a window to get a substring. The end of the window keeps forward and once it meets a character that is already in the window, update the start of the window. The unordered set can be replaced by an array of length 256.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> window;
int len=s.length();
int start=0,end=0;
int res=0;
for(;end<len;end++)
{
if(window.find(s[end])==window.end())
{
window.insert(s[end]);
if(end-start+1>res)
res=end-start+1;
}
else
{
while(s[start]!=s[end])
{
window.erase(s[start]);
start++;
}
start++;
}
}
return res;
}
};