从给定的字符串中按字母顺序查找最长的子字符串 [英] Finding the longest substring in alphabetical order from a given string
本文介绍了从给定的字符串中按字母顺序查找最长的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在研究一个问题,以便从给定的字符串中按字母顺序查找最长的子字符串.我在C ++方面有很多经验,但是对python来说绝对是新手.我已经写了这段代码
Ive been working on a question to find the longest substring in alphabetical order from a given string. I have a lot of experience in C++ but am absolutely new to python. Ive written this code
s = raw_input("Enter a sentence:")
a=0 #start int
b=0 #end integer
l=0 #length
i=0
for i in range(len(s)-1):
j=i
if j!=len(s)-1:
while s[j]<=s[j+1]:
j+=1
if j-i>l: #length of current longest substring is greater than stored substring
l=j-i
a=i
b=j
print 'Longest alphabetical string is ',s[i:j]
但是我不断收到此错误
Traceback (most recent call last):
File "E:/python/alphabetical.py", line 13, in <module>
while s[j]<=s[j+1]:
IndexError: string index out of range
我在这里做错了什么?同样,我对python还是很陌生!
What am I doing wrong here? Again, I am very new to python!
推荐答案
while s[j]<=s[j+1]:
j+=1
可以从字符串末尾开始
尝试:
while j!=len(s)-1 and s[j]<=s[j+1]:
j+=1
还要想一想当您找到一个字母顺序的序列的末尾时,这意味着什么-是否有任何理由检查一个更长的序列,该序列是从该序列中稍后的某个位置开始的?
Also think about what it means when you find the end of a sequence that's alphabetical - is there any reason to check for a longer sequence starting at some position later within that sequence?
这篇关于从给定的字符串中按字母顺序查找最长的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文