python - 最长子串
问题描述
s = 'abcabcbb'
def longsubstring(s):
if len(s)==0:
return 0
list1 = []
empty = ''
for i in s:
if i in empty:
list1.append(len(empty))
empty = ''
continue
else:
empty+=i
return max(list1)
longsubstring(s)
上面的代码在 s = 'abcabcbb' 时工作正常,但当 s = 'aab' 实际上为 2 时它返回 1。有人可以调试代码告诉我满足条件的地方错了吗。提前致谢。
解决方案
这是对您的代码的修改
s = 'aab'
def longsubstring(s):
if len(s)==0:
return 0
list1 = []
empty = ''
for i in range(0,len(s)):
empty=''
for j in range(i,len(s)):
if s[j] in empty:
list1.append(len(empty))
empty = ''
break
else:
empty+=s[j]
list1.append(len(empty))
return max(list1)
print(longsubstring(s))
推荐阅读
- css - 如何将此表格单元格居中在一行内?
- sql - H2 数据库:预期“所有、任何、某些、选择、从、与”
- java - 如何测量每个输入文件的 Xtend 翻译时间
- php - PHP 中的 SOAP 错误:OperationFormatter 遇到无效的消息正文
- spring-mvc - 在 Spring MVC 控制器中更改文件写入路径
- openshift - 流利的事件到 Splunk
- pattern-matching - “防护中的表达式无效,防护中不允许大小写”错误
- javafx - 带有JavaFx的浏览器MagicDraw插件
- asp.net - 从 ClaimsIdentity 获取 WindowsIdentity
- javascript - jQuery $.each() 不等待 $.Deferred()