zoukankan      html  css  js  c++  java
  • Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    1.o(n)时间复杂度的算法

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int sSize = s.size();
            if(sSize ==0){
                return 0;
            }
            int smap[260]={0};//smap存储的是字符s[i]的位置加1,加1是为了区别字符不存在的情况,字符不存在时,smap值为0
            smap[s[0]] = 1;
            int winStart = 0,winEnd = 1;//滑动窗口的首末位置
            int winMax = 1;
            for(int i=1;i<sSize;i++){
                int index = smap[s[i]]-1;
                if(index >=0 ){//说明s[i]字符存在,滑动窗口减小
                    for(int i=winStart;i<=index;i++){
                        smap[s[i]] = 0;
                    }
                    winMax = max(winEnd-winStart,winMax);
                    winStart = index+1;
                }
                smap[s[i]] = i+1;
                winEnd = i+1;
            }
            winMax = max(winEnd-winStart,winMax);
            return winMax;
        }
    };

    2.o(nlgn)时间复杂度的算法

    其实这题也可以用二分的思想来做,题目求的最大连续不存在重复元素的长度,这个长度最大是字符串s的长度,最小是0,我们可以用二分,开始假设结果是字符串长度的一半,

    然后把滑动窗口设置为这个长度,检验是否存在长度为其的连续串,根据结果设定low,high的值。

    代码比较简单,就不写了,可以参考下面这题:

    Minimum Size Subarray Sum

  • 相关阅读:
    ueditor富文本编辑在 asp.net MVC下使用步骤
    C#中Socket用法,多个聊天和单一聊天。
    事件与委托的联系和区别
    异步调用backgroudworker
    C#事件作用和用法
    如何遍历protected object转化为数组
    获取后台用户 token 的方法
    Magento2 中如何使用curl
    curl 错误排查方法
    Magento 2 REST API入门
  • 原文地址:https://www.cnblogs.com/zengzy/p/5026783.html
Copyright © 2011-2022 走看看