需要编写一个程序,打印变量的最长子串,其中的字母按字母顺序出现。
例如s='onsjdfjqiwkvftwfbx',它应该返回'dfjq'。
作为初学者,代码编写如下:
y=()
z=()
for i in range(len(s)-1):
letter=s[i]
while s[i]<=s[i+1]:
letter+=s[i+1]
i+=1
y=y+(letter,)
z=z+(len(letter),)
print(y[z.index(max(z))])
但是,上面的代码总是返回“IndexError:string index out of Range”。
它将产生所需的结果,直到我将其更改为range(len(s)-3)。
希望就以下方面征求意见:
>
为什么范围(len(s)-1)会导致这样的错误消息? 为了照顾到I+1之前的索引,我已经将范围值减少了1。 我的基本原理是,如果变量s的长度是14,它的索引在0-13之间,范围(14)产生值0-13。 然而,由于我的代码涉及到i+1个索引,范围减少了1以照顾这部分。
如何修改以上代码以产生正确的结果。 如果s='abcdefghijklmnopqrstuvwxyz',则上面带范围(len(s)-3)的代码再次返回“indexerror:string index out of range”。 为什么? 这个代码有什么问题?
欢迎任何帮助~
超范围索引的原因是,在内部while
循环中,您正在推进i
,而没有检查其范围。 您的代码也非常低效,因为您有嵌套循环,并且您正在进行大量相对昂贵的字符串连接。 没有级联的线性时间算法应该是这样的:
s = 'onsjdfjqiwkvftwfbcdefgxa'
# Start by assuming the longest substring is the first letter
longest_end = 0
longest_length = 1
length = 1
for i in range(1, len(s)):
if s[i] > s[i - 1]:
# If current character higher in order than previous increment current length
length += 1
if length > longest_length:
# If current length, longer than previous maximum, remember position
longest_end = i + 1
longest_length = length
else:
# If not increasing order, reset current length
length = 1
print(s[longest_end - longest_length:longest_end])