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 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.
题目含义:给你一串数字,解码成英文字母
分析
如果string中没有‘0’的存在,这道题就是简单的爬楼梯问题70. Climbing Stairs 并且其动归方程可以简单的记为:dp(i+1)=dp(i)+dp(i-1)
现在分析连续出现的两位数int tmp
那么它存在以下几种情况:
情况一
10 <= tmp <= 26 这个时候一定满足一个条件,dp(i)至少包含了dp(i-2)的内容,例如当子串为xxxx26,则一定能完成编码xxxxZ,而xxxx编码的个数为dp(i-2)。也就是说,从d[i-2]再跳一步(两位数26作为一个编码Z)可到达dp[i], 即dp[i] = dp[i] + dp[i-2]
情况二
1 <= tmp <= 9 ,例如当子串为xxxx26,则一定能完成编码xxxxBF,而xxxxB编码的个数为dp(i-1)。也就是说,从从d[i-1]再跳一步(单个位数6作为一个编码F)可到达dp[i], 即dp[i] = dp[i] + dp[i-1]
1 public int numDecodings(String s) { 2 if(s == null || s.length() == 0 || s.charAt(0) == '0') { 3 return 0; 4 } 5 int n = s.length(); 6 int[] dp = new int[n+1]; 7 dp[0] = 1; 8 dp[1] = 1; 9 for(int i = 2; i <= n; i++) { 10 int first = Integer.valueOf(s.substring(i-1, i)); 11 int second = Integer.valueOf(s.substring(i-2, i)); 12 if(first >= 1 && first <= 9) { 13 dp[i] += dp[i-1]; 14 } 15 if(second >= 10 && second <= 26) { 16 dp[i] += dp[i-2]; 17 } 18 } 19 return dp[n]; 20 }