剑指offer(48)--最长不重复字符子串

一.最长不重复字符子串长度

题目描述

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

思路分析

滑动窗口双指针

1.初始化头尾指针 head,tail;
2.tail 指针右移,判断 tail 指向的元素是否在 [head:tail] 的窗口内;

  • 如果窗口中没有该元素,则将该元素加入窗口,同时更新窗口长度最大值,tail 指针继续右移;
  • 如果窗口中存在该元素,则将 head 指针右移,直到窗口中不包含该元素。

3.返回窗口长度的最大值。

def lengthOfLongestSubstring(self, s: str) -> int:
        head=0
        tail=0
        if(len(s)<2):
            return len(s)
        res=1
        while tail<len(s)-1:
            tail+=1
            if s[tail] not in s[head:tail]:
                res=max(tail-head+1,res)
            else:
                while s[tail] in s[head:tail]:
                    head+=1
        return res

方法二

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        res=[]
        maxlen=0;
        curlen=0;
        for i in range(len(s)):
            val=s[i]
            if val not in res:
                res.append(val)
                curlen+=1
            else:
                index=res.index(val)
                res=res[index+1:]
                res.append(val)
                curlen=len(res)
            if(curlen>maxlen):
                maxlen=curlen
        return maxlen

二.最长不重复字符子串

def lengthOfLongestSubstring(s):
    head = 0
    tail = 0
    if (len(s) < 2):
        return len(s)
    res=1
    ans=[s[0]]
    while tail < len(s) - 1:
        tail += 1
        if s[tail] not in s[head:tail]:
            if res<len(s[head:tail+1]):
                res=tail-head+1
                ans.clear()
                ans.append(s[head:tail+1])
        else:
            while s[tail] in s[head:tail]:
                head += 1
    return ans
s=input()
s=s[1:len(s)-1]
print(lengthOfLongestSubstring(s))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值