LeetCode Day7:无重复字符的最长子串

发布于 2022-08-27  41 次阅读


题号:3
难度:Medium
链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters

思路

我的想法还是比较浅显直接的两重循环,表现实在太差,就不具体说了。

dalao解法

最后还是学习dalao的解法:

#include <string>
#include <math.h>

using std::max;
using std::string;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int last[128];
        for(int i=0;i<128;++i){
            last[i]=-1;
        }
        int n =s.size();
        int res=0;
        int start=0;
        for(int i=0;i<n;++i){
            int index=int(s[i]);
            start=max(start,last[index]+1);
            res=max(res,i-start+1);
            last[index]=i;
        }
        return res;
    }
};

我的思路的问题在于做了许多不必要的对比。因为我担心两个重复字符间还存在其他重复字符。

但dalao利用start=max(start,last[index]+1);,使得窗口起点总是在,“上一个窗口起点”和“上一个重复的后一个位置”间更靠后的一个位置。

而最初窗口起点在首位,解决了多重重复的问题。

全文完