按字母顺序查找python中最长的子字符串

2024-09-29 19:36:56 发布

您现在位置:Python中文网/ 问答频道 /正文

 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',那么您的程序应该打印beggh

在花了几个小时构建代码之后,我没有得到预期的结果。有人能看看我的代码,并指导我哪里出错。在


Tags: 代码程序lenlongestif顺序is字母
2条回答

这应该是你想要的。我用的是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))

我想说的是你想要的。与其比较字符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)

相关问题 更多 >

    热门问题