按abc顺序发送最长子字符串

时间:2018-06-12 22:51:05

标签: python

所以问题是在给定一个字符串s的情况下找到abc顺序中最长的子字符串,所以这段代码在某些情况下有效,但所以我定义它确实有用,我不知道为什么

s = 'vwjxxumjb'
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)

2 个答案:

答案 0 :(得分:1)

您的代码对您需要做的事情没有任何意义。你的代码只能从索引0开始按字母顺序找到最长的子字符串。这意味着当它到达第一个最长子字符串0的末尾时,它会停止并且不会再看起来。

s = 'vwjxxumjb'

count = 1
longest = 1
end = 0

for a in range(len(s) - 1):
    if s[a] <= s[a + 1]:      # is s[a] greater than or = to the next char in string?
        count += 1            # if it is, +1 to count
        if count > longest:   # if count is greater than longest (longest is current longest) continue, otherwise keep counting
            longest = count   # new longest is the current count because it is longest
            end = a + 1       # since end is in this if block, it counts the iteration where count was last greater than the longest
    else:                     # when count is never greater than longest again the longest will be the length of the longest string
        count = 1

start = end - longest + 1
"""
end is the last position in the longest string 
longest is length of the string 
so the end - longest characters = the start of string which is 
"""

print('Longest substring in alphabetical order is: ' + s[start:end + 1])
#prints the letters in s from position Start to End + 1 (+1 end does not include the index that it is given)

编辑: 一个完整的答案让Delirious Lettuce快乐。

答案 1 :(得分:1)

查看问题的最简单方法是逐步完成代码。您可以使用Python附带的内置调试器(或IDE附带的漂亮图形调试器,如果您使用它),或者只添加一堆print语句。但对于像这个问题一样小的东西,你可以使用在线可视化工具,如this one

起初,一切似乎进展顺利。它发现vwv更长并且记得那个。它看到j >= w为false,因此它会以j重新开始。

但是,在第16步,您有longest = 'vw'current = 'jx'len(current) > len(longest)为false,因此您点击else并设置{{1} }。然后,在步骤21,使用current = 'x',您再次点击其他并设置current = 'xx'。这就是它出错的地方。

显然,每次current = 'x'短于current = c时,您要在此处执行的操作都不会设置current,但仅在longest为假时才设置c >= current[-1]。这实际上只是简单地重新排列if / if / else逻辑。 (最小的变化是缩进第二个if,但我认为将else移动到它应该的位置可能更有意义,例如this。)

虽然我们正在使用它,但您应该尝试提供可能会破坏您的代码的示例,然后通过visualizer / debugger / print-fiesta运行它们。构建一套运行的单元测试是值得的,即使你还没有达到知道如何将代码包装在函数中并使用单元测试框架的程度。