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.
#include<iostream>
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i = 0, j = 0;
int str_len = s.length();
int substr_len = 0;
int substr_index = 0;
int pos_index = 0;
int sub_pos_index = 0;
while(i < str_len){
j = 0;
string substr = s.substr(i, str_len);
substr_index = substr.length();
while(j < substr_index){
sub_pos_index = substr.find(substr[j], j + 1);
if(sub_pos_index != string::npos){
substr_index = sub_pos_index;
substr = substr.substr(0, substr_index);
}
j++;
}
if(substr_len < j){
pos_index = i;
substr_len = j;
}
i++;
}
return substr_len;
}
};
int main()
{
Solution a;
int value = 0;
string s("abcabcbb");
value = a.lengthOfLongestSubstring(s);
cout << "length = " << value << endl;
system("pause");
return 0;
}