- Longest Substring Without Repeating Characters
Medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
一开始我读错题了,以为用map求子序列就行。。。
参考。https://cloud.tencent.com/developer/article/1377650
思路解析
建立一个256位大小的整型数组freg,用来建立字符和其出现位置之间的映射。
维护一个滑动窗口,窗口内的都是没有重复的字符,去尽可能的扩大窗口的大小,窗口不停的向右滑动。
(1)如果当前遍历到的字符从未出现过,那么直接扩大右边界;
(2)如果当前遍历到的字符出现过,则缩小窗口(左边索引向右移动),然后继续观察当前遍历到的字符;
(3)重复(1)(2),直到左边索引无法再移动;
(4)维护一个结果res,每次用出现过的窗口大小来更新结果res,最后返回res获取结果。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int freq[256] = {0};
int l = 0, r = 0; //滑动窗口为s[l...r]
int res = 0;
// 整个循环从 l == 0; r == 这个空窗口开始
// 到l == s.size(); r == s.size()-1 这个空窗口截止
// 在每次循环里逐渐改变窗口, 维护freq, 并记录当前窗口中是否找到了一个新的最优值
while(l<s.size())
{
if(r<s.size()&&freq[s[r]]==0)
{
freq[s[r]]++;
r++;
}
else //r已经到头 || freq[s[r]] == 1
{
freq[s[l]]--;
l++;
}
res=max(res,r-l);
}
return res;
}
};