91. Decode Ways -Python-Leetcode

91. 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 a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
E 26), "VF" (22 6), or "BBF" (2 2 6).ded as “BZ” (2 26), “VF” (22 6), 
or “BBF” (2 2 6).xplanation: It could be decoded a`s "BZ" (2

First

類似于臺階問題,當兩個數(shù)字組成小于26且大于10時。字符串s[:i]的所有可能解碼方式等于s[:i-1]+s[:i-2].
使用dp數(shù)組存儲中間值,定義dp[i]為從0到i之間的所有解碼方式, 則dp[i] = dp[i-1] + dp[i-2]
此外,我們還需要對0值進行處理

  1. 當字符s[i]等于'0',且'0'的前面一位大于'2'。比如'30',因為'30'無法編碼,所以返回0。
  2. 當字符s[i]等于'0',但前面一位小于'2'時,則只能讓'0'和前面一位進行編碼,因此可能方式等于dp[i-2]。
  3. 當字符s[i-1]等于'0'時,由于'0'只能跟s[i-2]的字符匹配解碼,因此s[i]只能選擇單獨解碼或和s[i+1]共同解碼
class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        if s and s[0] == "0":
            return 0
        dp = [1 for _ in range(len(s))]
        for i in range(1, len(s)):
            if s[i] == '0':
                if s[i-1: i+1] > '27' or s[i-1] == '0':
                    return 0
                else:
                    dp[i] = dp[i - 2]
            elif s[i-1: i+1] < '10':
                dp[i] = dp[i - 2]
            elif s[i-1: i+1] < '27':
                dp[i] = dp[i-1] + dp[i-2]
            else:
                dp[i] = dp[i-1]
        return dp[-1]


s = Solution()
print(s.numDecodings(''))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容