[英]python - find longest non-repeating substr in a string
Python 2.7 Getting stack out of index error in elif find the longest substr in a string (non repeating chars only) return the length Python 2.7在Elif中从索引错误中移出堆栈查找字符串中最长的substr(仅非重复字符)返回长度
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
This happens when stack
has only one element because you call stack.pop() twice in a row. 当
stack
只有一个元素时会发生这种情况,因为您连续两次调用stack.pop()。 I think what you meant is: 我认为您的意思是:
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])
However I think your code logic is still flawed: shouldn't you check if longest_substring
is actually longer than previous max_long_substring
value before updating it? 但是我认为您的代码逻辑仍然存在缺陷:在更新它之前,是否不应该检查
longest_substring
是否确实长于先前的max_long_substring
值?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.