当前位置 博文首页 > 三年研究生能改变多少:LeetCode第三题:无重复字符的最长子串py
英文题介绍:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
temp = ''
length = 0
for i in s:
if i not in temp:
temp+=i
length = max(length,len(temp))
else:
temp+=i
temp = temp[temp.index(i)+1:]
return length
1.本题所需知识点:
链接:http://www.runoob.com/python/python-strings.html
求字符串的下标,或叫索引。
2.我一开始犯的错:
错误代码>>>
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
temp = ''
length = 0
for i in s:
if i not in temp:
temp+=i
#length = max(length,len(temp))
else:
length = max(length,len(temp))
temp+=i
temp = temp[temp.index(i)+1:]
return length
这样会通过大部分实例,但是无法通过。一开始没有注意,后来发现犯的错误很简单:
当字符串为单个字符或者全是不重复的时候,根本不会进else循环中。
就是对于每个i,都只在if里就结束,else形同虚设,所以length就一直为0。
3.代码讲解
代码很简单,重点说一下两句代码:
首先,temp是存储遍历过的字符的。length是存储遇到的子字符串的最长长度的。
temp = temp[temp.index(i)+1:]
当遇到重复的时候,应该把重复的第一个去除,从后面一个开始算了。即:
子串为abc了,这时候再来一个a,那么新的字串应该是bca了。也就是把原字串的第一个a去掉,从b开始计,用时把新的a加上。