假设我们有一个小写字母的单词列表,我们必须找到所有单词具有相同首字母的最长连续子列表的长度。
因此,如果输入类似于[“ she”,“ sells”,“ seashells”,“ on”,“ the”,“ seashore”]],则输出为3,因为三个连续的单词分别是“ she”,“ sells” ”,“贝壳”,都具有相同的首字母“ s”。
为了解决这个问题,我们将遵循以下步骤-
最大长度:= 0
curr_letter:=空,curr_length:= 0
对于单词中的每个单词,
curr_length:= curr_length + 1
maxlength:= maxlength的最大值,curr_length
curr_letter:= word [0],curr_length:= 1
如果curr_letter为null或curr_letter与word [0]不同,则
除此以外,
返回maxlength和curr_length的最大值
让我们看下面的实现以更好地理解-
class Solution: def solve(self, words): maxlength = 0 curr_letter, curr_length = None, 0 for word in words: if not curr_letter or curr_letter != word[0]: maxlength = max(maxlength, curr_length) curr_letter, curr_length = word[0], 1 else: curr_length += 1 return max(maxlength, curr_length) ob = Solution() words = ["she", "sells", "seashells", "on", "the", "seashore"] print(ob.solve(words))
["she", "sells", "seashells", "on", "the", "seashore"]
输出结果
3