leetcode_algorithm3 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

给你一个字符串,找到它的无重复字符的最长子串。

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is
"abc"
, with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is
"b"
, with the length of 1.

 思路:

看到这个题目的时候,不知道为什么脑海里想到了kmp,然后就用了类似于kmp的思想进行求解。首先是建立一个空列表用来存储子串,如果下一个字符没有出现当前子串里面,则把这个字符添加到子串里面,形成新的子串,如果下一个字符出现在当前的子串里,则添加后做删除处理。每一次子串列表有变化时,都要进行长度更新,最后得到最长的子串长度。

def lengthOfLongestSubstring(self, s: str) -> int:
        if len(s)>1:
            i = 0
            temp = [s[0]]
            max = 0
            while i < len(s) - 1:
                i = i + 1
                if s[i] not in temp:
                    temp.append(s[i])
                    max_temp = len(temp)
                else:
                    temp.append(s[i])
                    temp = temp[temp.index(s[i])+1:]
                    max_temp = len(temp)
                if max_temp > max:
                    max = max_temp
                else:
                    continue
            return max
        else:
            return len(s)   

while里面的if和else里面都有球长度的语句,为什么不移到判断外面呢?当然,这样做事可以的,但是效率会变慢,至于为什么,过程比较复杂。

猜你喜欢

转载自blog.csdn.net/qq_30124241/article/details/87928707