您的位置:首页 > 编程语言 > Python开发

3.Longest Substring Without Repeating Characters Leetcode Python

2015-01-27 05:11 453 查看
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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python Array
相关文章推荐