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.
The subject is very similar to that of climbing stairs. Use an array to do the DP.
But the difference is that there are several limitations:
First: S[i-1] can not be 0, if S[I-1] is 0, num[i] can only be equal to num[i-2]
Second, the first character in S[i-2,i-1] cannot be 0, and Integer.parseint (S.substring (i-2,i)) must have an integer from 0 to 27
1 Public classSolution {2 Public intnumdecodings (String s) {3 if(s = =NULL|| S.length () = = 0)return0;4 int[] num =New int[S.length () +1];5Num[0] = 1;6NUM[1] = S.charat (0)! = ' 0 '? 1:0;7 for(inti = 2; I <= s.length (); i++){8 if(S.charat (i-1)! = ' 0 ')9Num[i] = num[i-1];Ten if(S.charat (i-2)! = ' 0 ' && integer.parseint (s.substring (i-2,i)) < 27) OneNum[i] + = Num[i-2]; A } - returnnum[s.length ()]; - } the}
Decode Ways Java Solutions