s = 'abcabcabc'
i = 0
j = 1
longestSubString = ''
realString = ''
while (j < len(s)):
if i == 0:
longestSubString = s[i]
if (s[j] >= s[i]):
longestSubString = longestSubString + s[i]
if len(longestSubString) > len (realString):
realString = longestSubString
i += 1
j += 1
else:
longestSubString = ''
i += 1
j += 1
print ("Longest SubString is: " + realString)
编写一个程序,打印s中最长的子字符串,其中字母按字母顺序出现。例如,如果s ='azcbobobegghakl',那么您的程序应该打印
花费数小时构建代码后,我没有得到理想的结果。有人可以看看我的代码并指导我,无论我错在哪里。
答案 0 :(得分:1)
这应该做你想要的。我使用Python3,但它也适用于Python2
s = 'azcbobobegghakl'
res = ''
tmp = ''
for i in range(len(s)):
tmp += s[i]
if len(tmp) > len(res):
res = tmp
if i > len(s)-2:
break
if s[i] > s[i+1]:
tmp = ''
print("Longest substring in alphabetical order is: {}".format(res))
答案 1 :(得分:0)
我会说这是你想要的。您需要比较它们的索引,而不是比较字符s[j] > s[i]
。您可以使用string.ascii_lowercase.index(s[i])
。
Get character position in alphabet
编辑:重构一下以使其更具可读性
import string
s = 'azcbobobegghakl'
i = 0
currentSubString = ''
longestSubString = ''
while (i < len(s)):
positionCurrent = string.ascii_lowercase.index(s[i])
positionPrevious = string.ascii_lowercase.index(s[i-1])
currentCharacter = s[i]
i += 1
if (positionCurrent != positionPrevious + 1):
currentSubString = ''
currentSubString += currentCharacter
if len(longestSubString) < len(currentSubString):
longestSubString = currentSubString
print("Longest SubString is: " + longestSubString)