A message containing letters from
A-Z
is being encoded to numbers using the following mapping:'A' -> 1 'B' -> 2 ... 'Z' -> 26Given 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 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
我写的动态规划比较麻烦,结果:
Success
Runtime: 1 ms, faster than 97.05% of Java online submissions for Decode Ways.
Memory Usage: 34.2 MB, less than 100.00% of Java online submissions for Decode Ways.
class Solution {
public int numDecodings(String s) {
if(s==null||s.length()==0){return 0;}
if(s.charAt(0)=='0'){return 0;}
if(s.length()==1){return 1;}
int[] memo=new int[s.length()];
memo[0]=1;
int inst=(s.charAt(0)-'0')*10+s.charAt(1)-'0';
if(inst>=10&&inst<=26&&inst!=10&&inst!=20){memo[1]=2;}
else if((inst>0&&inst%10!=0)||inst==10||inst==20) memo[1]=1;
int index=2;
while(index<memo.length){
int sec=s.charAt(index)-'0';
int fst=s.charAt(index-1)-'0';
fst=sec+fst*10;
if(sec>0&&sec<=9){memo[index]+=memo[index-1];}
if(fst<=26&&fst>=10){memo[index]+=memo[index-2];}
index++;
}
return memo[s.length()-1];
}
}
讨论里有个简洁一些的,放上来给大家参下:
public class Solution {
public int numDecodings(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int n = s.length();
int[] dp = new int[n+1];
dp[0] = 1;
dp[1] = s.charAt(0) != '0' ? 1 : 0;
for(int i = 2; i <= n; i++) {
int first = Integer.valueOf(s.substring(i-1, i));
int second = Integer.valueOf(s.substring(i-2, i));
if(first >= 1 && first <= 9) {
dp[i] += dp[i-1];
}
if(second >= 10 && second <= 26) {
dp[i] += dp[i-2];
}
}
return dp[n];
}
}
这个会慢一点2ms