用 Python 编写程序查找所有首字母相同的单词

pythonserver side programmingprogramming更新于 2026/1/12 7:40:17

假设我们有一个小写字母的单词列表,我们必须找到所有单词首字母相同的最长连续子列表的长度。

因此,如果输入为 ["she", "sells", "seashells", "on", "the", "seashore"],则输出将为 3,因为三个连续的单词为 "she", "sells", "seashells",所有单词的首字母均为 's'。

为了解决这个问题,我们将遵循以下步骤 −

  • maxlength := 0
  • curr_letter := Null,curr_length := 0
  • 对于 words 中的每个单词,执行
    • 如果 curr_letter 为 null 或 curr_letter 与 word[0] 不同,则
      • maxlength := maxlength、curr_length 的最大值
      • curr_letter := word[0],curr_length := 1
    • 否则,
      • curr_length := curr_length + 1
  • 返回 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

相关文章


有用资源