Longest Substring Without Repeating Characters My Submissions Question
Total Accepted: 109306 Total Submissions: 524897 Difficulty: MediumGiven a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<string> substrs;
string str;
for(int i = 0; i < s.size(); ++i){
if(str.find(s[i]) == string::npos){
str.push_back(s[i]);
}
else{
substrs.push_back(str);
str.clear();
i = substrs.size()-1; //从这个重复的字符处开始再次向后查找
}
if(i == s.size()-1){ //考虑到一个字符串中的字符全部都不相同的情况
substrs.push_back(str);
}
}
int maxlen = 0;
for(int i = 0; i < substrs.size(); ++i){
if(substrs[i].size() > maxlen){
maxlen = substrs[i].size();
}
}
return maxlen;
}
};
这个思路很简单,但是时间复杂度太高;