Python 基礎知識簡單

計算給定數字序列的可能解碼

「計算給定數字序列的可能解碼」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 count_decodings(digits),它接受一個數字字串並傳回對其進行解碼的可能方法數,其中 'A' = 1、'B' = 2、...、'Z' = 26。

例如,「12」可以解碼為「AB」(1, 2) 或「L」(12),有 2 種方式。

如果字串在無效位置包含「0」(例如,前導「0」或「30」),則這些路徑無效且不應計數。

約束條件
  • 1 <= len(digits) <= 20
  • digits contains only characters '0' through '9'

範例

Example 1
Input
count_decodings('12')
Output
2
Explanation

'12' can be decoded as 'AB' (1,2) or 'L' (12). So 2 ways.

Example 2
Input
count_decodings('226')
Output
3
Explanation

'226' can be decoded as 'BBF' (2,2,6), 'BZ' (2,26), or 'VF' (22,6). So 3 ways.

Example 3
Input
count_decodings('06')
Output
0
Explanation

'06' cannot be decoded because '0' has no letter mapping and '06' is not a valid code.

Need a Hint?
考慮使用特定於數字的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。