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
复制代码

 

posted @   dahu1  Views(160)  Comments(0Edit  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2017-04-05 Python操作MongoDB(PyMongo模块的使用)
2017-04-05 python操作json数据格式--基础
2017-04-05 linux shell awk实现实时监控网卡流量脚本
2017-04-05 Python 的十个自然语言处理工具
点击右上角即可分享
微信分享提示