Python 字符串中最长的字符序列

Python longest character sequence in a string

我正在学习 python,遇到了实验室问题。需要计算字符串中一个s个字符的最长序列,只能使用for循环等基本工具。

我想出的代码有效,但感觉我在使用不适当的逻辑添加一个 sequence_extended 变量和一个额外的 space。但是,如果没有此扩展名,则序列是例如sssdssss 计算仅适用于第一个序列。

是否有办法避免该扩展?我试过寻找一个想法,但解决方案通常是使用我们还不允许使用的功能,例如列表等

sequence = input('enter a line: ')
sequence_extended = sequence + ' '
counter = 0
final_counter = 0

for symbol in sequence_extended:
  if symbol == 's':
    counter += 1
    
  else:
    if counter > final_counter:
        final_counter = counter
        counter = 0


print("The longest sequence of 's':", final_counter)
sequence = "sssdssss"
max_len = 0

for i in range(len(sequence)):
    if sequence[i] == "s":
        j = i
        length = 0
        while j < len(sequence) and sequence[j] == "s":
            length += 1
            j += 1
        if length > max_len:
            max_len = length

print("The longest sequence of 's':", max_len)

事实上,我想出了一个更简单的选择:

sequence = input('enter a sequence: ')

first_counter = 0
second_counter = 0

for symbol in sequence:
  if symbol == 's':
    first_counter += 1
  if symbol != 's':
    first_counter = 0  
  if second_counter < first_counter:
    second_counter = first_counter
print("the longest sequence of 's':", second_counter)

这似乎是解决问题的最佳方案。以防其他人有这样的实验室需要解决。