使用 Python 打印最长的字母子字符串,对于并列,打印第一个子字符串 [英] Print the longest alphabetical substring using Python and for ties, print the first substring
问题描述
假设 s 是一串小写字符.编写一个程序,打印 s 中字母按字母顺序出现的最长子串.
Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
例如,如果 s = 'azcbobobegghakl',那么你的程序应该打印
For example, if s = 'azcbobobegghakl', then your program should print
按字母顺序排列的最长子串是:beggh
Longest substring in alphabetical order is: beggh
在平局的情况下,打印第一个子字符串.例如,如果 s = 'abcbcd',那么你的程序应该打印
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
按字母顺序排列的最长子串是:abc
Longest substring in alphabetical order is: abc
这是我找到的代码.我如何在上面给出的关于关系的问题中实现后一个条件?
Here's the code I found. How do I implement the latter condition in the question given above regarding ties?
*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)))*
推荐答案
我会通过以下方式解决问题:
I'd approach the problem the following way:
- 让我们定义两个字符串:递增字母的
current
字符串和当前longest
字符串. - 两个字符串都用第一个字母初始化.(这样我们就可以随时阅读他们的最后一封信.)
- 然后我们遍历输入字符串
s
(从第二个字符开始). - 如果当前字符
c
满足要求c >= current[-1]
,我们将其添加到当前解决方案中. - 我们可能将
current
字符串存储为longest
. - 如果
c
不满足排序要求,我们从一个新的解决方案current = c
开始. - 最后,我们打印
longest
字符串.
- Let's define two strings: The
current
string of increasing letters and the currentlylongest
string. - Both strings are initialized with the first letter. (This way we can always read their last letter.)
- Then we iterate over the input string
s
(starting with the second character). - If the current character
c
fulfills the requirementc >= current[-1]
, we add it to the current solution. - We possibly store the
current
string aslongest
. - If
c
does not fulfill the ordering requirement, we start with a new solutioncurrent = c
. - Finally, we print the
longest
string.
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
<小时>
如何修复您的代码.提到的条件:
在比较len(result) >= len(final)
时使用>
代替>=
,即只更新final
解决方案,如果它更长,但不是如果它具有相同的长度.
Use >
instead of >=
in the comparison len(result) >= len(final)
, i.e. only update the final
solution if it is longer, but not if it has the same length.
考虑 Dylans 的评论
你说得对.我更新了代码和描述以正确处理 s
以最长的字母子字符串结尾的情况.(将 else:
向下移动两行就足够了.)
You're right. I updated both code and description to correctly handle the case when s
ends with the longest alphabetical substring. (Moving else:
two lines down was sufficient.)
这篇关于使用 Python 打印最长的字母子字符串,对于并列,打印第一个子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!