首页 > 解决方案 > 最长子串

问题描述

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。有人可以调试代码告诉我满足条件的地方错了吗。提前致谢。

标签: pythonstringalgorithmsubstring

解决方案


这是对您的代码的修改

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))

推荐阅读