题目描述
Given 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.
思路:滑动窗口
eg: abcabcbb,
a
ab
abc
bca
cab
......
类似与deque,若子串中有当前字符,则把子串中当前字符及前边的字符都删除并清空对应的标志位,最后把当前字符添加到尾部;
若子串中没有当前字符,则直接把当前字符添加到子串尾部,并设置对应的标志位。
代码:
/*longest-substring-without-repeating-characters*/
int lengthOfLongestSubstring(string s);
bool charIsInSubString(deque<char> d, char c);//判断当前字符是否已在子串中
int lengthOfLongestSubstring_2(string s);//改进了判断当前字符是否已在子串中。
int lengthOfLongestSubstring_3(string s);//改进了deque,用两个变量begin和end来模拟deque。
int main(){
//char c = 'a';
//deque<char> d;
//d.push_back('a');
//d.push_back('b');
//cout << charIsInSubString(d, c) << endl;
string s = "wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco";
//string s= "abcabcbb";
//string s= "bbbbb";
cout << lengthOfLongestSubstring_3(s) << endl;
return 0;
}
int lengthOfLongestSubstring_3(string s){
bool flag[255] = {0};
int max=0;
int count = 0;
int i;
int begin=0, end=0;
for(i = 0; i < s.length(); ++i){
if(!flag[s[i]]){
flag[s[i]] = true;
++end;
++count;
if(count > max)
max = count;
}
else{
int j;
for(j = begin; s[j] != s[i]; ++j){
flag[s[j]] = false;
++begin;
--count;
}
++begin;
--count;
++end;
++count;
if(count > max)
max = count;
}
}
return max;
}
int lengthOfLongestSubstring_2(string s){//运行时间8ms,内存492k
bool flag[255] = {0};
//ostream_iterator<char> out_it(cout, " ");
int max=0;
deque<char> d;
int count = 0;
int i;
for(i = 0; i < s.length(); ++i){
if(!flag[s[i]]){
flag[s[i]] = true;
d.push_back(s[i]);
++count;
if(count > max)
max = count;
}
else{
deque<char>::iterator dIter = d.begin();
for(; *dIter != s[i]; ++dIter){
flag[d.front()] = false;
d.pop_front();
--count;
}
d.pop_front();
--count;
d.push_back(s[i]);
++count;
if(count > max)
max = count;
}
//copy(d.begin(), d.end(), out_it);
//cout << " " << "count: " << count << " max: "<< max << endl;
}
return max;
}
int lengthOfLongestSubstring(string s){//运行时间20ms,内存492k
ostream_iterator<char> out_it(cout, " ");
int max=0;
deque<char> d;
int count = 0;
int i;
for(i = 0; i < s.length(); ++i){
if(!charIsInSubString(d, s[i])){
d.push_back(s[i]);
++count;
if(count > max)
max = count;
}
else{
deque<char>::iterator dIter = d.begin();
for(; *dIter != s[i]; ++dIter){
d.pop_front();
--count;
}
d.pop_front();
--count;
d.push_back(s[i]);
++count;
if(count > max)
max = count;
}
//copy(d.begin(), d.end(), out_it);
//cout << " " << "count: " << count << " max: "<< max << endl;
}
return max;
}
bool charIsInSubString(deque<char> d, char c){
deque<char>::iterator dIter;
dIter = find(d.begin(), d.end(), c);
if(dIter == d.end())
return false;
else
return true;
}