A message containing letters from was A-Z
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 is "12"
2.
Problem Solving Ideas:
The typical dynamic programming
Judging dp[i-1], dp[i-2] is valid
Recurrence Formula:dp[i] + = Dp[i-1] if (s (i-1, i) is valid (1-9)) + Dp[i-2] (if s (i-2, i)) are valid (10-26))
Base Case:dp[0] =1, dp[1] = 1 (s (0) is valid) or 0 (s (0) are not valid)
Java Code:
Public classSolution { Public intnumdecodings (String s) {if(s = =NULL|| S.length () = = 0 | | S.equals ("0")){ return0; } int[] DP =New int[S.length () +1]; //base case:dp[0] dp[1]Dp[0] = 1; if(IsValid (s.substring (0,1)) {dp[1] = 1; }Else{dp[1] = 0; } for(inti = 2; I<= s.length (); i++){ if(IsValid (S.substring (i-1, i))) {Dp[i]+ = Dp[i-1]; } if(IsValid (S.substring (i-2, i))) {Dp[i]+ = Dp[i-2]; } } returndp[s.length ()]; } Public BooleanIsValid (String s) {if(S.charat (0) = = ' 0 ') { return false; } intValue = Integer.parseint (s);//Integer.parseInt:translate string to int returnValue >=1 && value <= 26; }}
Reference:
1. http://www.programcreek.com/2014/06/leetcode-decode-ways-java/
2. http://www.cnblogs.com/springfor/p/3896162.html
Leetcode Decode Ways