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

LeetCode 3. 无重复字符的最长子串 Python

2018-06-26 14:29 603 查看
给定一个字符串,找出不含有重复字符的最长子串的长度。示例:给定 
"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)

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: