简繁EN

LeetCodeNo. 010

[LeetCode with Python] 91. Decode Ways

Contents

Problem

Problem page: https://leetcode.com/problems/decode-ways/
Topics: Dynamic Programming, String
Difficulty: Medium

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.


Analysis

(This is probably a one-dimensional DP problem. It's basically the Fibonacci sequence, so why did I use two rows???)
It's a DP problem. Besides handling the boundary cases, I also had to watch out for '0'. A '0' can be part of a valid two-digit code like '10' or '20', but a '0' anywhere else is invalid input. Like atoi, this problem has an unclear description. It doesn't say that you should "decode as much of the string as possible", so at first, whenever I found an extra '0', I assumed decoding had failed and returned 0. After I submitted it, I found out that was wrong. Also, the input parameter s can be an empty string. Judging by the test results, I should return 0 in that case, but the problem doesn't make that clear either.
You can save memory on a lot of DP problems. Here, too, there's no need for an n * 2 two-dimensional array. I only need to keep two rows, which takes 2 * 2 space.
One last thing worth mentioning is a trick I just learned. At first I was going to write a swap function like I would in C and use a temporary variable tmp to swap the two references solu_arr1 and solu_arr2. Then I found out I could just write solu_arr1, solu_arr2 = solu_arr2, solu_arr1. Hooray for Python! (It also shows I came to Python late...)


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if None == s or 0 == len(s) or '0' == s[0]:
return 0
solu_arr1 = [0, 1]
solu_arr2 = [0, 0]
for i in range(1, len(s) + 1):
cur_ch = s[i - 1]
last_ch = s[i - 2] if 1 != i else ''
if cur_ch >= '1' and cur_ch <= '9':
solu_arr2[0] = solu_arr1[0] + solu_arr1[1]
else:
solu_arr2[0] = 0
double_ch = last_ch + cur_ch
if '' == last_ch or '0' == last_ch or int(double_ch) > 26:
solu_arr2[1] = 0
else:
solu_arr2[1] = solu_arr1[0]
solu_arr1, solu_arr2 = solu_arr2, solu_arr1 # swap

return solu_arr1[0] + solu_arr1[1]

Article link: https://xnerv.wang/en/leetcode-decode-ways/