Python程式:查詢具有相同首字母單詞的最長連續子列表的長度


假設我們有一個包含小寫字母字串的列表,稱為 words。我們需要找到最長連續子列表的長度,其中每個單詞的首字母相同。

因此,如果輸入類似於 words = ["she", "sells", "seashells", "on", "the", "sea", "shore"],則輸出將為 3,最長連續子列表為 ["she", "sells", "seashells"]。每個單詞的首字母都是 's'。

為了解決這個問題,我們將遵循以下步驟:

  • cnt := 1

  • maxcnt := 0

  • prev_char := 空字串

  • 對於 words 中的每個單詞,執行以下操作:

    • 如果 prev_char 為空,則:

      • prev_char := 單詞的首字母

    • 否則,當 prev_char 與單詞的首字母相同時,則:

      • cnt := cnt + 1

    • 否則:

      • prev_char := 單詞的首字母

      • cnt := 1

    • maxcnt := maxcnt 和 cnt 的最大值

  • 返回 maxcnt

示例

讓我們檢視以下實現以更好地理解

def solve(words):
   cnt = 1
   maxcnt = 0
   prev_char = ""
   for word in words:
      if prev_char == "":
         prev_char = word[0]
      elif prev_char == word[0]:
         cnt += 1
      else:
         prev_char = word[0]
         cnt = 1
      maxcnt = max(maxcnt, cnt)
   return maxcnt

words = ["she", "sells", "seashells", "on", "the", "sea", "shore"]
print(solve(words))

輸入

["she", "sells", "seashells", "on", "the", "sea", "shore"]

輸出

3

更新於: 2021年10月11日

164 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告