Leetcode 滑动窗口
Leetcode 3
3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
- 思路
使用滑动窗口算法解体,编写滑动窗口时注意边界值和终止条件; 窗口right值从-1开始,因为要取right+1处数组的值,所以要求right+1<=high,对于aa
类的数组,会出现left>right的情况(left=right+1),此时len为0。
int lengthOfLongestSubstring(string s) {
int freqs[256] = {0};
int low = 0;
int high = s.size() - 1;
int left = low;
int right = -1; // 注意此处从-1开始;
int maxLen = 0;
while (right + 1 <= high) { // 要保证s.at(right+1)不越界;
if (freqs[s.at(right + 1)] == 0) {
right++;
freqs[s.at(right)]++;
} else { // 可以出现left=right+1的情况,此时len为0;
freqs[s.at(left)]--;
left++;
}
maxLen = max(maxLen, right - left + 1);
}
return maxLen;
}