Longest Substring Without Repeating Characters

xiaoxiao2021-02-28  30

问题描述

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

Examples:

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.

我的想法非常的简单,从左到右依次遍历,如果下一个字符next不在当前的字串s中,那就添加进字串s=s+next,如果在字串中next in s,说明已经由相同的了,先将字串s保存下来,将字串的头移动到相同字符的下一个位置,依次遍历,最后会得到很多个子串[s1,s2,s3...]最后找出最长的字串。

class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if s == '':return 0 maxlen = 0 start = 0 #子串开始的位置 end = 0 #子串最后的位置 s += s[-1] #为了好处理abcabcbb->abcabcbbb while end < len(s): # end = 0 substr = s[start:end] # 子串 endstr = s[end] if endstr in substr: if end - start > maxlen: maxlen = end - start start += substr.index(endstr)+1 end = end + 1 return maxlen
转载请注明原文地址: https://www.6miu.com/read-2628224.html

最新回复(0)