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.
answer:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<string> substr;
substr.push_back("");
int index = 0;
for(int i = 0; i < s.length(); i ++){
char c = s[i];
string tempStr = substr[index];
// cout << "now string: " << tempStr << endl;
int pos = substr[index].find(c,0);
if(pos != substr[index].npos){
string temp = substr[index].substr(pos + 1,substr[index].length());
substr.push_back(temp);
index ++;
substr[index] += c;
// cout << "new string: " << substr[index] << endl;
}
else{
substr[index] += c;
// cout << "update string: " << substr[index] << endl;
}
}
int max = 0;
vector<string>::iterator it = substr.begin();
while(it != substr.end()){
if((*it).length() > max)
max = (*it).length();
it ++;
}
return max;
}
};