Decode Ways

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.

C++:
01 class Solution {
02 public:
03     int numDecodings(string s) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int result=0;
07         int n=s.size();
08         if(n==0)
09             return result;
10         vector<int> A(n+1);
11         A[n]=1;
12         if(s[n1]==‘0’)
13         {
14             A[n1]=0;
15         }
16         else
17         {
18             A[n1]=1;
19         }
20         for(int i=n2;i>=0;i)
21         {
22             A[i]=0;
23             string t=s.substr(i,1);
24             int singleDigit=stoi(t);
25             if(singleDigit>0)
26             {
27                 A[i]+=A[i+1];
28             }
29             else
30             {
31                 continue;
32             }
33             string d=s.substr(i,2);
34             int doubleDigit=stoi(d);
35             if((doubleDigit>=1)&&(doubleDigit<=26))
36             {
37                 A[i]+=A[i+2];
38             }
39         }
40         return A[0];
41     }
42 };
Advertisements
This entry was posted in Dynamic programming, String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s