📅  最后修改于: 2023-12-03 14:50:47.781000             🧑  作者: Mango
对于一个给定的字符串(只包含小写字母),编写一个程序来找到字符串中最长的连续自母母串(连续字母顺序的最大长度)。如果存在多个长度相同的连续字母顺序的最大长度,返回最后出现的一个。
输入
string = "abcdd"
输出
2
解释
最长连续字母顺序为dd
,长度为2。
以下是一个解决问题的示例代码:
def find_longest_consecutive_sequence(string):
longest_sequence = ""
current_sequence = ""
for i in range(len(string)):
if i > 0 and string[i] == string[i-1]:
current_sequence += string[i]
else:
current_sequence = string[i]
if len(current_sequence) >= len(longest_sequence):
longest_sequence = current_sequence
return len(longest_sequence)
# 测试示例
string = "abcdd"
print(find_longest_consecutive_sequence(string))
以上代码中,我们定义了一个函数find_longest_consecutive_sequence
来查找给定字符串中的最长连续字母子串的长度。我们使用两个变量longest_sequence
和current_sequence
来分别记录最长子串和当前子串。在循环中,我们比较当前字符和前一个字符是否相同,以确定是否连续。如果相同,则将当前字符添加到当前子串中,否则重新开始一个新的子串计数。每当我们找到一个更长的子串时,我们更新longest_sequence
的值。最后,我们返回最长子串的长度作为结果。
以上代码的输出为:
2
这表明给定字符串"abcdd"中,最长连续字母顺序为dd
,长度为2。
希望这个解决方案对您有所帮助!