LeetCode0003——longest substring without repeating characters——Sliding Window

今天在一个题库上看到了这道题,点进去一看很久之前竟然做过:
在这里插入图片描述
首先明确最长字串和最长子序列概念是不同的,前者必须要连续,后者只需要遵从源串的序列顺序即可。也正是因为字串必须连续,这就可以采纳滑动窗口算法来解决这个问题。

一般来说,滑动窗口算法其实就是用两个指针(索引值)圈定了一个线性序列的范围,然后大致按照此规律进行求解:
1.窗口上界持续向前推进
2.窗口下界同时检验着当前圈出来序列是否满足题目要求
3.如果不满足那么就修改窗口下界到下一个满足要求的位置

结束条件一般是窗口上界到达数组终点。
以下是此题的代码:

int lengthOfLongestSubstring(string s) {
    
    
        if(s.size() == 0)
            return 0;

        /*
            Max is the maximum length of substring
            Behind is the lower bound of sliding window
            Ahead is the upper bound of sliding window 
        */
        int Max = 1;
        int Behind = 0;
        int Ahead = 1;

        while(Ahead <= s.size() - 1)
        {
    
    
            /*test if the current sequence satisfies the request*/
            for(int i = Behind ; i < Ahead ; ++i)
                if(s[i] == s[Ahead])
                    /*if duplicated char is detected, jump to next position*/
                    Behind = i + 1;
            
            /*modify the max length of substring if needed*/
            if(Ahead - Behind + 1 > Max)
                Max = Ahead - Behind + 1;      

            /*continue to increase the upper bound [Ahead]*/          
            ++Ahead;
        }
        return Max;
    }

猜你喜欢

转载自blog.csdn.net/zzy980511/article/details/115835205