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 void way(string s,int& n,int index,int last)
02 {
03     if(index==s.size()1){
04         if((last==0)||(last*10+s[index]‘0’<=26))
05             n++;
06         return;
07     }
08     if(last==0){
09         int t=s[index]‘0’;
10         way(s,n,index+1,t);
11         way(s,n,index+1,0);
12     }else{
13         int t=last*10+s[index]‘0’;
14         if(t>26)
15             return;
16         way(s,n,index+1,0);
17     }
18 }
19 
20 int numDecodings(string s) {
21     int n=0;
22     way(s,n,0,0);
23     return n;
24 }

The above code is a recursive way of dynamic programming. Usually, it is not efficient since the result of subproblem is not reused!! We need to find an iterative way to solve it!

C++:
01 int numDecodings(string s) {
02         int n=s.size();
03         vector <int> r(n+1);
04         r[n]=1;
05         if((s[n1]>‘9’)||(s[n1]<‘0’))
06             return 0;
07         if(s[n1]!=‘0’)
08             r[n1]=1;
09         for(int i=n2;i>=0;i){
10             int k=s[i]‘0’;
11             if((k>9)||(k<0))
12                 return 0;
13             if(k==0)
14                 r[i]=0;
15             else if(k*10+s[i+1]‘0’<=26)
16                 r[i]=r[i+1]+r[i+2];
17             else
18                 r[i]=r[i+1];
19         }
20         return r[0];
21 }
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