Jea*_*amp 5 python string python-2.7
我正在学校学习 Python 2.7 课程,他们告诉我们创建以下程序:
假设 s 是一串小写字符。
编写一个程序,打印 s 中字母按字母顺序出现的最长子串。
例如,如果 s = azcbobobegghakl ,那么您的程序应该打印
按字母顺序排列的最长子串是:beggh
如果是平局,则打印第一个子字符串。
例如,如果 s = 'abbcbcd',那么你的程序应该打印
按字母顺序排列的最长子串是:abc
我写了以下代码:
s = 'czqriqfsqteavw'
string = ''
tempIndex = 0
prev = ''
curr = ''
index = 0
while index < len(s):
curr = s[index]
if index != 0:
if curr < prev:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index]
tempIndex=index
elif index == len(s)-1:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index+1]
prev = curr
index += 1
print 'Longest substring in alphabetical order is: ' + string
Run Code Online (Sandbox Code Playgroud)
老师还给了我们一系列的测试串来尝试:
s = 'czqriqfsqteavw'
string = ''
tempIndex = 0
prev = ''
curr = ''
index = 0
while index < len(s):
curr = s[index]
if index != 0:
if curr < prev:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index]
tempIndex=index
elif index == len(s)-1:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index+1]
prev = curr
index += 1
print 'Longest substring in alphabetical order is: ' + string
Run Code Online (Sandbox Code Playgroud)
所有这些都工作正常,除了最后一个,它产生以下答案:
按字母顺序排列的最长子串是:cz
但应该说:
按字母顺序排列的最长子串是:avw
我已经检查了代码一千遍,没有发现任何错误。请你帮助我好吗?
这些行:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index+1]
Run Code Online (Sandbox Code Playgroud)
彼此都不同意。如果新的最佳字符串是,s[tempIndex:index+1]那么您应该在 if 条件中比较该字符串的长度。将它们更改为彼此一致可以解决问题:
if len(s[tempIndex:index+1]) > len(string):
string = s[tempIndex:index+1]
Run Code Online (Sandbox Code Playgroud)