思路:
维持两个指针来计算最长不重复子串长度
如果没有重复的字符,就左指针不动,右指针右移
如果有一个字符重复了,那么左指针往右移动
如何确定重复:用一个容器,将对应字符的ascii作为下标,该下标里的值存放的是这个字符的下一个位置。也就是当某个字符重复了,左边的指针就应该移动到下一个位置。
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int lengthOfLongestSubstring(string s) {
vector<int> m(128, 0);
int len = 0;
int i = 0;
for (int j = 0; j < s.size(); j++) {
i = max(i, m[s[j]]);
m[s[j]] = j + 1;
len = max(len, j - i + 1);
}
cout << len << endl;
return len;
}
int main()
{
string s = "abcdab";
lengthOfLongestSubstring(s);
system("pause");
return 0;
}
参考:
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/longest-substring-without-repeating-characters-b-2/
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/cdong-tai-gui-hua-jie-fa-by-happyfire/