image.png
看到这个题目我第一反应是好简单QAQ,五分钟搞出。然后这是我的代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time2019/8/22
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = []
res = []
for x in s:
if x not in l:
l.append(x)
else:
res.append(len(l))
i = l.index(x)
l = l[i+1:]
l.append(x)
res.append(len(l))
return max(res) if res else 0
if __name__ == '__main__':
solution = Solution()
str = "pwwkew"
max_length = solution.lengthOfLongestSubstring(str)
print(max_length)
但是在提交测试的时候在第407个测试用例出现了错误:
image.png
如下,我反应了十分钟才明白到底哪出问题了,我还一度认为测试用例的结果是官方人员写错了。。。真是头猪:内心OS:dvdf,没错啊!!最长就是2啊,后来我反应过来还有子串vdf。。。
这样看来是我根本逻辑错了,我在遍历子串的时候,在遇到重复字段时候下意识地将当前索引直接跳转到重复位置,也就是在遇到形容dvdf时候,第二个d我直接跳到d上,没考虑从v开始。。。
下面是网上大神写的,简洁高效(哭泣
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = []
res = []
for x in s:
if x not in l:
l.append(x)
else:
res.append(len(l))
i = l.index(x)
l = l[i+1:]
l.append(x)
res.append(len(l))
return max(res) if res else 0
巧用切片,保存了最大不重复子串。