Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
第一种方法是利用左指针和右指针选出substring 然后判断substring里面是否有重复,如果没有重复右指针向右继续前进,否则左指针前进。
在这个过程中maintain maxlen=max(maxlen,len(substring))
代码如下,这个算法时间是n^2 但是过不了最后的一个长的case:
class Solution:
# @return an integer
def unique(self,str):
d={}
for elem in str:
if elem not in d:
d[elem]=1
else:
return False
return True
def lengthOfLongestSubstring(self, s):
left=0
right=0
maxlen=0
while right<=len(s):
substr=s[left:right]
if self.unique(substr):
maxlen=max(maxlen,len(substr))
right+=1
else:
left+=1
return maxlen第二种算法对第一中算法进行优化
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
if len(s)<=1:
return len(s)
left=0
right=0
maxlen=0
substr=''
for right in range(len(s)):
if s[right] not in substr:
substr=substr+s[right]
else:
maxlen=max(maxlen,len(substr))
while s[left]!=s[right]:
left+=1
left+=1
substr=s[left:right+1]
return max(maxlen,len(substr))
本文介绍了一种算法,用于解决给定字符串中无重复字符最长子串的问题。通过使用双指针技术,该算法在优化的基础上解决了复杂度较高的案例。
335

被折叠的 条评论
为什么被折叠?



