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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。