LeetCode3. Longest Substring Without Repeating Characters(最长不重复子串)

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/


Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.


解题思路:O(n^2)的算法我不说了,敲了一版果断TLE,这里说说O(n)的;


1.首先i,j都从起始位置开始,j不断右移直到s[j]重复出现,此时情况如下左图所示;

2.如果是暴利O(n^2)的算法,会从i+1的位置重复上一步骤,但是我们会发现,从i+1作重复的步骤是没有意义的,因为它不管再长都会在j的位置出现重复,也就是说,其长度始终小于i~j的长度;

3.那么,i从哪一个位置开始才有意义的,答案是从C的那个位置处,也就是重复出现元素s[j]第一次出现位置的下一个,即下右图所示;


理解了整个过程,你会发现算法复杂度是O(n) + O(n) = O(n)的,每次j右移结束更新最大长度max即可;





参考代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int i,j,ans;
        i = j = ans = 0;
        int len = s.size();
        bool f[300];
        memset(f,0,sizeof(f));
        while(j<len){
            if(!f[s[j]]){
                f[s[j]] = 1;
                j++;
            }
            else{
                ans = max(ans,j-i);
                while(s[i]!=s[j]){
                    f[s[i]] = 0;
                    i++;
                }
                i++;
                j++;
            }
        }
        ans = max(ans,len-i);//边界
        return ans;
    }
};





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值