给定一个字符串,找出不含有重复字符的最长子串的长度。
示例:
给定 "abcabcbb"
,没有重复字符的最长子串是 "abc"
,那么长度就是3。
给定 "bbbbb"
,最长的子串就是 "b"
,长度是1。
给定 "pwwkew"
,最长子串是 "wke"
,长度是3。请注意答案必须是一个子串,"pwke"
是 子序列 而不是子串。
class Solution(object):
def lengthOfLongestSubstring(self, s):
temp = res = ""
for item in s:#对于字符串s中的每个字符
if item not in temp:#如果这个字符不在temp当中
temp += item
if len(temp) > len(res): res = temp
else:
i = temp.index(item)#找到索引
if i == len(temp)-1: temp = item#如果到达末尾
else:temp = temp[i+1:] + item#没达到末尾
if len(temp) > len(res): res = temp
return len(res)