Longest Substring Without Repeating Characters
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.
Subscribe to see which companies asked this question
代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)==0:
return 0
else:
max=1
j=1
L=[s[0]]
for i in range(len(s)-1):
while j<=len(s)-1: #调节j,省时间
if s[j] not in L:
L.append(s[j])
j+=1
else:
if len(L)>max:
max=len(L)
i+=L.index(s[j])+1
L=L[L.index(s[j])+1:j]
break
if j==len(s):
if len(L)>max:
max=len(L)
return max