您的位置:首页 > 其它

LeetCode 3. Longest Substring Without Repeating Characters

2017-02-14 16:32 555 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: