思路1:
greedy+hash,从左到右扫描
反例: abcade
思路2:
每次遇到重复字符时不是全部重新开始,而是弹出元素直到不重复
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
if(len == 0){
return 0;
}
queue<char> cq;
set<char> dict;
int cnt = 0, mmax = -1;
for(int i = 0; i < len;){
//cnt = 0;
bool conflict = false;
char recchar;
int recid;
for(int j = i; j < len; ++j){
if(dict.find(s[j]) == dict.end()){
dict.insert(s[j]);
cq.push(s[j]);
cnt++;
mmax = max(mmax, cnt);
}
else{
conflict = true;
recchar = s[j];
recid = j;
break;
}
}
if(conflict){
while((!cq.empty()) && cq.front() != recchar){
char qtop = cq.front();
cq.pop();
dict.erase(qtop);
}
if(!cq.empty()){
cq.pop();
//cq.push(recchar);
dict.erase(recchar);
}
i = recid;
cnt = dict.size();
}
else{
break;
}
}
return mmax;
}
};