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) {
string max_str = "";
string temp = "";
char ch;
for(int i=0; i<s.length(); i++)
{
ch = s[i];
int idx = temp.find(ch);
if(idx==string::npos)
{
temp += s[i];
}
else
{
temp = temp.substr(idx+1);
temp += s[i];
}
if(temp.length()>=max_str.length())
{
max_str = temp;
}
}
return max_str.length();
}
};