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.
1 class Solution: 2 def numDecodings(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 if s==‘‘: 8 return 0 9 10 dp = [0] *(len(s)+1) 11 dp[0] = 1 12 dp[1] = int(s[0]!=‘0‘) 13 14 for i in range(2,len(s)+1): 15 if(s[i-1]!=‘0‘): 16 dp[i]=dp[i-1] 17 18 if s[i-2:i]>‘09‘ and s[i-2:i]<‘27‘: 19 dp[i] +=dp[i-2] 20 21 return dp[len(s)] 22 ## 1 2 1 23 ## 1 0 1 24 25 26 #dp[i] = dp[i-1] if s[i] != "0" 27 # +dp[i-2] if "09" < s[i-1:i+1] < "27"