问题
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