跳到主要内容

Decode Ways

描述

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

分析

跟第???节Climbing Stairs很类似,不过多加一些判断逻辑。

代码

# Decode Ways
# Dynamic programming, time complexity O(n), space complexity O(1)
class Solution:
def numDecodings(self, s: str) -> int:
if not s or s[0] == '0':
return 0

prev = 0
cur = 1
# For a string of length n, there are n+1 steps
for i in range(1, len(s) + 1):
if s[i-1] == '0':
cur = 0

if i < 2 or not (s[i-2] == '1' or
(s[i-2] == '2' and s[i-1] <= '6')):
prev = 0

tmp = cur
cur = prev + cur
prev = tmp

return cur

相关题目