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.
思路:
用动态规划Dynamci Programming来解。一位数时不能为0,两位数不能大于26,其十位上的数也不能为0。用哈希表来存或者用两个变量来存。
State: dp[i]
Function: dp[i] = dp[i - 1] (if i - 1 != 0) + dp[i - 2] (if i - 2 == 1 or i - 2 == 2 and i -1 < = 6)
Initialize: dp[0] = 0, dp[1] = 1
Return: dp[n]
Java 1:
public class Solution { public int numDecodings(String s) { if (s.isEmpty() || (s.length() > 1 && s.charAt(0) == ‘0‘)) return 0; int[] dp = new int[s.length() + 1]; dp[0] = 1; for (int i = 1; i < dp.length; ++i) { dp[i] = (s.charAt(i - 1) == ‘0‘) ? 0 : dp[i - 1]; if (i > 1 && (s.charAt(i - 2) == ‘1‘ || (s.charAt(i - 2) == ‘2‘ && s.charAt(i - 1) <= ‘6‘))) { dp[i] += dp[i - 2]; } } return dp[s.length()]; } }
Java 2:
public class Solution { public int numDecodings(String s) { if (s.isEmpty() || (s.length() > 1 && s.charAt(0) == ‘0‘)) return 0; int prev = 1, prev_prev = 0; for (int i = 0; i < s.length(); i++) { int cur = 0; if (s.charAt(i) != ‘0‘) { cur = prev; } if (i > 0 && (s.charAt(i - 1) == ‘1‘ || (s.charAt(i - 1) == ‘2‘ && s.charAt(i - 1) <= ‘6‘))) { cur += prev_prev; } prev_prev = prev; prev = cur; } return prev; } }
Python:
class Solution(object): def numDecodings(self, s): if len(s) == 0 or s[0] == ‘0‘: return 0 prev, prev_prev = 1, 0 for i in xrange(len(s)): cur = 0 if s[i] != ‘0‘: cur = prev if i > 0 and (s[i - 1] == ‘1‘ or (s[i - 1] == ‘2‘ and s[i] <= ‘6‘)): cur += prev_prev prev, prev_prev = cur, prev return prev