使用Python打印最长的字母子字符串,对于ties,打印第一个子字符串

2024-09-27 07:27:05 发布

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

假设s是一个小写字符字符串。 编写一个程序,打印字母按字母顺序出现的s的最长子串。

例如,如果s='azcbobobebeghakl',那么您的程序应该打印

Longest substring in alphabetical order is: beggh

对于ties,打印第一个子字符串。例如,如果s='abcbcd',则程序应打印

Longest substring in alphabetical order is: abc

这是我找到的密码。在上面关于领带的问题中,我如何实现后一个条件?

    *s = raw_input('provide string: ')
    result = []
    final = []
    for letters in s:
        result = result + [letters]        
        if result == sorted(result) and len(result) >= len(final):
            final = result            
        elif result != sorted(result):
            result = [result[len(result)-1]]        
    print('Longest substring in alphabetical order is: '+(''.join(final)))*

Tags: 字符串in程序lenlongestis字母order
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:05

我会用下面的方法来解决这个问题:

  • 让我们定义两个字符串:递增字母的current字符串和当前的longest字符串。
  • 两个字符串都用第一个字母初始化。(这样我们就可以读到他们的最后一封信。)
  • 然后我们迭代输入字符串s(从第二个字符开始)。
  • 如果当前字符c满足要求c >= current[-1],则将其添加到当前解决方案中。
  • 我们可能将current字符串存储为longest
  • 如果c不满足排序要求,我们将从一个新的解决方案current = c开始。
  • 最后,我们打印longest字符串。
s = "azcbobobegghakl"
longest = s[0]
current = s[0]
for c in s[1:]:
    if c >= current[-1]:
        current += c
        if len(current) > len(longest):
            longest = current
    else:
        current = c
print "Longest substring in alphabetical order is:", longest

如何修复代码wrt。上述条件:

在比较中使用>而不是>=,也就是说,仅当final解决方案的长度时才更新它,但如果它的长度相同则不更新。


考虑Dylans的评论

你说得对。当s以最长的字母顺序子字符串结尾时,我更新了代码和描述以正确处理这种情况。(向下移动两行就足够了。)

相关问题 更多 >

    热门问题