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.
Solution:
DP.这道破题好难做。真的,会举例子,举出好的例子很重要!
2
21
210
分析210。如果最后位是零,则dp[3]跟dp[2]没关系,dp[3]有几种组合就看substring(i-2,i)也就是2和10的组合。如果不是零,那么总的组合数就是原先dp[2]的组合数加上可能的dp[1]组合数。检查10这两个数,如果处于0-26之间,则能跟2组合,也就是多了dp[i-2]的decode方式。dp[i]+=dp[i-2]。否则如果大于26或者小于10(中间一个数为零必然不能成组合),不能组合。嗯,说完我自己都晕了。
public class Solution { public int numDecodings(String s) { if(s.length()==0||s.charAt(0)=='0') { return 0; } int[] dp=new int[s.length()+1]; dp[0]=1; dp[1]=1; for(int i=2;i<=s.length();i++) { if(s.charAt(i-1)!='0') { dp[i]=dp[i-1]; } if(Integer.valueOf(s.substring(i-2,i))<=26&&Integer.valueOf(s.substring(i-2,i))>=10) { dp[i]+=dp[i-2]; } } return dp[dp.length-1]; } }