algorithm - 编写一个程序,打印 s 中字母按字母顺序出现的最长子串

标签 algorithm substring alphabetical

代码运行良好,输出看起来也不错。但是我的 print 在 for 循环中,这让我怀疑编码是否正确:

s = 'azcbobobegghakl'
i = 0
increase = 0
longest = 1
for i in range(len(s) - 1):
        if s[i+1] >= s[i]:
           increase +=1
        else:
            if increase > longest:
               longest = increase
               print ("
Longest substring in alphabetical order is:"+""+s[i-longest:i+1])

            increase =0

最佳答案

我会这样写:

s = 'abcaakabcdeakk'
i = 0
increase = 0
longest = 1
longest_end = 1
for i in range(len(s)):
        if i < len(s)-1 and s[i+1] >= s[i]:
           increase += 1
        else:
            if increase > longest:
               longest = increase
               longest_end = i
            increase = 0
print ("Longest substring in alphabetical order is:" + s[longest_end-longest:longest_end+1])

关于algorithm - 编写一个程序,打印 s 中字母按字母顺序出现的最长子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44887941/

相关文章:

Python 正则表达式查找所有单个字母字符

python - 如何根据输入的数字生成所有可能的字母组合列表

c++ - 一个数的所有除数的除数之和

c++ - 检查所有数组成员是否具有相同的值

python - pandas DataFrame 多个子串匹配,还将一行的特定匹配子串放入新列

java - 如何从String中获取 "1.2"格式的字符串?

java - 如何按字母顺序获取数组的值?

algorithm - k 连续调用 bst 中的树后继

algorithm - 线条简化图像处理

arrays - 如果单词以后缀之一结尾,则标记为 1