Longest Substring Without Repeating Characters

求最长不重复子字符串

题目来源:

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

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.

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

先外面一个循环,遍历每个的时候,再遍历当前位置之后的所有字符串,设一个tmp用来存储,如果发现重复的就break,但是这个容易TLE

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.不遍历后面了,看前面的

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

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
原文地址:https://www.cnblogs.com/dahu-daqing/p/8723936.html