Longest Substring Without Repeating Characters

求最长不重复子字符串spa

题目来源:code

https://leetcode.com/problems/longest-substring-without-repeating-characters/blog

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

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.get

1,两个循环,复杂度O(n2)string

先外面一个循环,遍历每一个的时候,再遍历当前位置以后的全部字符串,设一个tmp用来存储,若是发现重复的就break,可是这个容易TLEit

def find_long_norepeat_str(one_str):
    #没经过,复杂度过高,两个for循环,复杂度 O(n2)
    res_list=''
    length=len(one_str)
    for i in range(length):
        tmp=one_str[i]
        for j in range(i+1,length):
            if one_str[j] in tmp:
                break
            else:
                tmp+=one_str[j]
        if len(tmp)> len(res_list):
            res_list=tmp
    return res_list

2.不遍历后面了,看前面的for循环

仍是先循环一遍 ,遍历每一个的时候,找之前的字符串,如"abcabcbb",第一个abc正常跑,记录数量res,到了第2个a的时候,发现以前有重复了a,那就从下一个位置开始find,cur记录当前s[i]之前出现过的那个位置的,curbegin是记录find从哪一个位置开始找,一旦发现有重复,curbegin在下一次循环中就后移了,res就是记录  你当前的位置 - 搜索起点的位置,也就是最大不重复子串。复杂度要好点。class

def find_sonstr_lis(s):
    if len(s)<=1:
        return len(s)
    res=1
    curbegin=0
    for i in range(len(s)):
        cur=s.find(s[i],curbegin,i)
        if cur!=-1:
            if i-curbegin>res:
                res=i-curbegin
                value=s[curbegin:i]
            curbegin=cur+1
    if s.find(s[-1],curbegin,len(s)-1)==-1:
        res=max(res,len(s)-curbegin)
    return  res
相关文章
相关标签/搜索