Python 2.7 在elif中获取堆栈的索引错误 找到字符串中最长的子字符串(仅限非重复字符) 返回长度
from pythonds.basic import Stack
def longest_nonrepeating_len(s):
"""find longest non-repeating substring and return its length"""
if len(s) < 1:
return []
longest_substring = 0
max_long_substring = 0
stack = Stack()
stack.push(s[0])
for char in range(0,len(s)):
if stack.isEmpty():
stack.push(s[char])
longest_substring = 1
max_long_substring = 1
continue
if s[char] != stack.pop():
longest_substring += 1
stack.push(s[char])
max_long_substring = longest_substring
elif s[char] == stack.pop():
longest_substring = 0
stack.push(s[char])
return max_long_substring
ERROR:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 23, in longest_nonrepeating_len
IndexError: pop from empty list
>>> longest_nonrepeating_len("abccd")
3
>>> longest_nonrepeating_len("ffff")
1
答案 0 :(得分:2)
当stack
只有一个元素时会发生这种情况,因为你连续两次调用stack.pop()。我想你的意思是:
pop = stack.pop()
if s[char] != pop:
longest_substring += 1
stack.push(s[char])
max_long_substring = longest_substring
elif s[char] == pop:
longest_substring = 0
stack.push(s[char])
但是我认为您的代码逻辑仍存在缺陷:在更新之前,您是否应该检查longest_substring
实际上是否比之前的max_long_substring
值更长?