Python程式:統計排序母音字串


假設我們有一個數字n,我們需要找到由母音(a, e, i, o, u)組成的、大小為n的字串數量,並且這些字串按字典序排序。如果一個字串s對於所有有效的索引i,s[i]都等於或在字母表中排在s[i+1]之前,則稱其為字典序排序。

因此,如果輸入是n = 2,則輸出將是15,因為有很多這樣的字串,例如["aa", "ae", "ai", "ao", "au", "ee", "ei", "eo", "eu", "ii", "io", "iu", "oo", "ou", "uu"]。

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

  • 如果n等於1,則
    • 返回5
  • count := 一個大小為6的陣列,初始值都為1
  • 對於i從3到n,執行:
    • count[1] := count[1]+count[2]+count[3]+count[4]+count[5]
    • count[2] := count[2]+count[3]+count[4]+count[5]
    • count[3] := count[3]+count[4]+count[5]
    • count[4] := count[4]+count[5]
  • total := 0
  • 對於i從1到5,執行:
    • total := total + i*count[i]
  • 返回total

示例

讓我們來看下面的實現,以便更好地理解:

def solve(n):
   if n==1:
      return 5
   count = [1 for i in range(6)]
   for i in range(3,n+1):
      count[1] = count[1]+count[2]+count[3]+count[4]+count[5]
      count[2] = count[2]+count[3]+count[4]+count[5]
      count[3] = count[3]+count[4]+count[5]
      count[4] = count[4]+count[5]
   total = 0
   for i in range(1,6):
      total += i*count[i]
   return total

n = 2
print(solve(n))

輸入

2

輸出

15

更新於:2021年10月5日

591 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告