经典问题 滑动窗口
思路
滑动窗口,保证每个窗口里字母都是唯一的

使用 vector<int> m 来记录一个字母如果后面出现重复时,i 应该调整到的新位置
21. 所以每次更新的时候都会保存 j + 1 ,即字母后面的位置
j 表示子串的最后一个字母,计算子串长度为 j - i + 1
答题
C++
int lengthOfLongestSubstring(string s) {
vector<int> m(128, 0);
int ans = 0;
int i = 0;
for (int j = 0; j < s.size(); j++) {
i = max(i, m[s[j]]);
m[s[j]] = j + 1;
ans = max(ans, j - i + 1);
}
return ans;
}
模拟
作者:ikaruga
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/longest-substring-without-repeating-characters-b-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号