question:
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.
思路:
借助hash,当发现有重复的字符时,从重复字符的下一个字符开始进行遍历。
#include <iostream>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> cnt;
cnt.clear();
int maxValue = 0;//考虑空字符串的情况,返回零
int length = s.length();
int i = 0;
for(; i < length; i++) {
if(!cnt.count(s[i])) {
cnt[s[i]] = i;
if(i == length-1) {
maxValue = max(maxValue, (int)cnt.size());
}
}
else {
maxValue = max(maxValue, (int)cnt.size());
i = min(cnt[s[i]], length-1);
cnt.clear();
}
}
return maxValue;
}
};
int main()
{
Solution *obj = new Solution();
string str;
while(cin >> str) {
int res = obj->lengthOfLongestSubstring(str);
cout << res << endl;
}
return 0;
}
/***
abcabcd
fabcdefgh
abfabcdefghi
***/
思路2:
“滑动窗口”
比方说 abcabccc 当你右边扫描到abca的时候你得把第一个a删掉得到bca,
然后”窗口”继续向右滑动,每当加到一个新char的时候,左边检查有无重复的char,
然后如果没有重复的就正常添加,如果有重复的话就左边扔掉一部分(从最左到重复char这段扔掉),在这个过程中记录最大窗口长度
详细参考
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int i = 0, j = 0;
int maxLen = 0;
bool exist[256] = { false };
while (j < n) {
if (exist[s[j]-0]) {
maxLen = max(maxLen, j-i);
while (s[i] != s[j]) {
exist[s[i]-0] = false;
i++;
}
i++;
j++;
} else {
exist[s[j]-0] = true;
j++;
}
}
maxLen = max(maxLen, n-i);
return maxLen;
}
};