查找字符按字母顺序排列的最长子字符串的复杂程序的问题



我发现这个解决方案似乎有效:

def longest_ascending(s):
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]:
current.append(character)
else:
matches.append(current)
current = [character]
matches.append(current)
return "".join(max(matches, key=len))

打印(longest_ascending(

字符和索引不是总是相同的字符吗?

例如,如果 'ababc' 存储在 s 变量中,则第一次 ''for'' 迭代将经过 ''if 'b'>=s[1]'',这基本上是''if 'b'>='b''',第二个将包含语句''if 'a'>='a'等等,这意味着''else'块永远不会真正被执行。

那么,该程序究竟是如何运作的呢?

请注意,您正在枚举s[1:],但索引s。如果 s 是 'abc',则枚举中的第一对是(0, 'b')s[0]'a'

最新更新