LeetCode3-无重复字符的最长子串

题目描述:
LeetCode3-无重复字符的最长子串_第1张图片
最容易想到也是最“傻”的解法:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        res,a=[],[]
        if len(s)==0:
            return 0
        if s==' ' or len(s)==1:
            return 1
        for i in range(len(s)-1):
            t=[]
            re=''
            t.append(s[i])
            re+=s[i]
            for j in range(i+1,len(s)):
                if s[j] not in t:
                    t.append(s[j])
                    re=re+s[j]
                else:
                    break
            res.append(re)
        for i in range(len(res)):
            a.append(len(res[i]))
        return max(a) 

LeetCode3-无重复字符的最长子串_第2张图片
滑动窗口:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        if not s:return 0
        lookup = list()
        n = len(s)
        max_len = 0
        cur_len = 0
        for i in range(n):
            val = s[i]
            if not val in lookup:
                lookup.append(val)
                cur_len+=1
            else:
                index = lookup.index(val)
                lookup = lookup[index+1:]
                lookup.append(val)
                cur_len = len(lookup)
            if cur_len > max_len:max_len = cur_len
        return max_len

LeetCode3-无重复字符的最长子串_第3张图片

你可能感兴趣的:(leetcode)