简体   繁体   中英

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

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. 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM