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 " , it could be decoded as " AB " (1 2) Or " L " ().
The number of ways decoding is "12" 2.
Basic ideas
Similar to the question climbing stairs
Before I, there are two ways to decode:
1. Section i-1 potential energy independent decode
2. I-2 and I-1, two together as a whole decode
Then the number of DEOCDE methods is the sum of the above two paths.
This code on the Leetcode, the implementation time is 5ms.
Class Solution {public: int numdecodings (string s) { if (S.empty ()) return 0; int w2 = 1; int w1 = s[0]! = ' 0 '? 1:0; int w = W1; for (int i=2; i<=s.size (); i++) { w = (s[i-1] = = ' 0 ')? 0:w1; if (s[i-2] = = ' 1 ' | | s[i-2] = = ' 2 ' && s[i-1] >= ' 0 ' && s[i-1] <= ' 6 ') w + = W2; W2 = W1; W1 = w; } Return w; }};
Decode Ways--Leetcode