150強訪談中等

解碼方式

“解碼方式”問題的詳細指南和 Python 實作。

問題陳述

中等

包含 A-Z 字母的訊息可以使用以下映射編碼為數字:

“A”->“1”

“B”->“2”

……

“Z”->“26”

要解碼編碼訊息,必須將所有數字分組,然後使用上面的反向映射映射回字母。例如,「11106」可以映射為:

- “AAJF”與分組 (1 1 10 6)

- “KJF”與分組 (11 10 6)

請注意,分組 (1 11 06) 無效,因為「6」與「06」不同,因此「06」無法對應到「F」。

給定一個僅包含數字的字串 s,傳回解碼它的方法數。

寫一個函數 numDecodings(s: str) -> int

約束條件
  • 1 <= len(s) <= 100
  • s contains only digits and may contain leading zero(s)

範例

Example 1
Input
s = "12"
Output
2
Explanation

"12" could be decoded as "AB" (1 2) or "L" (12).

Example 2
Input
s = "226"
Output
3
Explanation

"226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Example 3
Input
s = "06"
Output
0
Explanation

"06" cannot be mapped to 'F' because of the leading zero.

Need a Hint?
考慮使用一維 DP 特定的資料結構,例如集合或堆。
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 資源

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