美文网首页Python学习
Leetcode【03】无重复字符的最长子串(Python)

Leetcode【03】无重复字符的最长子串(Python)

作者: zzx_知者巷 | 来源:发表于2022-01-19 11:31 被阅读0次

题目

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度
示例 1: 输入: s = "abcabcbb"。 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2: 输入: s = "bbbbb"。因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3: 输入: s = "pwwkew"。因为无重复字符的最长子串是 "wke",所以其长度为 3。

思路

  1. 设置临时字符temp,初始为空"",最长子串长度MaxLength,初始为0;
  2. 遍历输入字符s(i=0),
     2-1. 若s[i]不在temp中,则将s[i]加入temp;
     2-2. 否则
       记录当前temp长度tempLength,若大于MaxLength则更新MaxLength
       移除temp中已有s[i]及之前的元素,添加s[i],作为新的temp
     2-3. i++

实现

class Test:
    def __init__(self):
        pass

    def getL(self, li):
        maxL = 0; temp_maxL = 0
        i = 0
        temp=[]
        while i<len(li):
            if li[i] in temp:  # 第i个元素重复存在
                index = temp.index(li[i])
                temp = temp[index+1:]  # 删除重复元素及其前面的部分
                temp.append(li[i])  # 末尾添加
                maxL = temp_maxL if maxL < temp_maxL else maxL  # 更新长度
            else:
                temp.append(li[i])  # 末尾添加
            temp_maxL = len(temp)
            # print(i, temp)
            i += 1
        maxL = temp_maxL if maxL < temp_maxL else maxL  # 最后一个元素经过else
        return maxL

if __name__ == "__main__":
    Mlength = Test().getL("pwwkewa")
    print(Mlength)


相关文章

网友评论

    本文标题:Leetcode【03】无重复字符的最长子串(Python)

    本文链接:https://www.haomeiwen.com/subject/ttmecrtx.html