题目:
给定一个字符串,找出不含有重复字符的最长子串的长度。(python)
示例:
给定 "abcabcbb"
,没有重复字符的最长子串是 "abc"
,那么长度就是3。
给定 "bbbbb"
,最长的子串就是 "b"
,长度是1。
给定 "pwwkew"
,最长子串是 "wke"
,长度是3。请注意答案必须是一个子串,"pwke"
是 子序列 而不是子串。
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/
方法一:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
str1 = []
temp = 0
x = 0
for i in range(0,len(s)):
for j in range(i,len(s)):
if s[j] in str1:
x = len(str1)
break
else:
str1.append(s[j])
x = len(str1)
if x>temp:
temp = x
str1 = []
else:
str1=[]
return temp
本方法无法提交。。。因为后面的测试时间比较长,超时了,但是结果是对的
方法二:
https://blog.csdn.net/together_cz/article/details/77533121 这个是下面代码的博客,我把他复制过来为了写注释
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res_list=[]
length=len(s)
for i in range(length):
tmp=s[i]
for j in range(i+1, length):
if s[j] not in tmp:
tmp+=s[j]
else:
break
res_list.append(tmp)
res_list.sort(lambda x,y:cmp(len(x),len(y))) //把res_list中的字符串按长短排序
res = res_list[-1] //取最长的一个
return len(res) //返回其长度
这个是我在网上找的,但是,也是提交不上去,因为res_list[-1]报错:索引超出范围。。。明明可以运行。好气啊!
后来补充:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
ans = 0
dic = {} //创建一个空字典
i = 0
for j in range(n):
if s[j] in dic:
i = max(dic.get(s[j]),i) //若字符已存在,则将子串的开头索引(i)向后移动
ans = max(ans,j-i+1) //子串长度取当前最长值
dic[s[j]] = j+1 //字典中键为字符串中的字母,值为该字符索引
return ans
这个代码是我把阅读解答里面的java代码改成python了,可以提交通过。