Finding the longest substring in alphabetical order from a given string

流过昼夜 提交于 2019-12-19 11:53:42

问题


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]

But I keep on getting this error

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

What am I doing wrong here? Again, I am very new to python!


回答1:


while s[j]<=s[j+1]:
    j+=1

Can run off the end of the string.

Try:

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?




回答2:


You can use this simple piece of code to achieve what you want

s = 'kkocswzjfq'
char = ''
temp = ''
found = ''
for letter in s:
    if letter >= char:
        temp += letter
    else:
        temp = letter
    if len(temp) > len(found):
        found = temp
    char = letter
print(found)


来源:https://stackoverflow.com/questions/19604825/finding-the-longest-substring-in-alphabetical-order-from-a-given-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!