部落格網域名稱: http://www.xnerv.wang
原題頁面: https://oj.leetcode.com/problems/decode-ways/
題目類型:動態規劃
難度評價:★★★★
本文地址: http://blog.csdn.net/nerv3x3/article/details/2921931
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問題,需要注意的除了邊界條件的處理,還有關於'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。
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]