简繁EN

LeetCodeNo. 010

【LeetCode with Python】 91. Decode Ways

目錄

題目

原題頁面:https://leetcode.com/problems/decode-ways/
題目型別:Dynamic Programming, String
難度評價: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.


分析

(這個應該是一個一維DP問題,本質是裴波拉契數列,為什麼我用了兩行???)
DP問題,需要注意的除了邊界條件的處理,還有關於'0'的注意點。'0'本身可以構成'10','20'這樣合法的雙位元組碼,但其它情況的'0'就是異常資料了。這道題目跟atoi一樣,都屬於題意描述不清晰,題意本身並沒有說清楚要“儘量多地解碼出字串”,因此一開始我一旦發現有多餘的'0'就直接認為解碼失敗範圍0,結果提交後發現不對。此外,輸入的引數s也可能是個空串,從驗證的結果看來這種情況下應該返回0,題目也沒有說清楚。
另外對於很大一部分DP題目,記憶體都是可以最佳化的,這裡也不必採用n * 2大小的二維陣列,只需保留兩行,即2 * 2的空間消耗即可。
最後,還要特別說明一下新學到的一招。起先還想像C語言一樣寫個swap函式,用一個臨時變數tmp來交換solu_arr1和solu_arr2兩個引用,後來發現竟然可以用solu_arr1, solu_arr2 = solu_arr2, solu_arr1這種簡便的寫法,大讚Python!(同時也說明了我學Python是半路出家……)


程式碼

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]

本文地址:https://xnerv.wang/zh-tw/leetcode-decode-ways/