(14) Recursion: Print Encoding

I am Computer Science Graduate and Web Developer.
Difficulty: Hard
Problem Statement: Given a string of numbers you need to find corresponding alphabets.
Approach: There are a few things that you need to keep in mind while solving this question. If we have a single number and it is zero then an answer is not possible. If we have a length of string greater than 1 then we can spit the solution in two parts.
The first part will be to consider the first letter and solve the rest string. The second part will be to consider two numbers such that they are less than equal to 26 and solve the rest of the string.
#include <bits/stdc++.h>
using namespace std;
void solve(string que, string asf)
{
if (que.size() == 0)
{
cout << asf << endl;
return;
}
else if (que.size() == 1)
{
char ch = que[0];
if (ch == '0') return;
else
{
int chv = ch - '0';
char code = (char)('a' + chv - 1);
cout << asf + code << endl;
}
}
else
{
char ch = que[0];
string roq = que.substr(1);
if (ch == '0') return;
else
{
int chv = ch - '0';
char code = (char)('a' + chv - 1);
solve(roq, asf + code);
}
string ch12 = que.substr(0, 2);
string roq12 = que.substr(2);
int ch12v = ((int)ch12[0] - '0') * 10 + ((int)ch12[1] - '0');
if (ch12v <= 26)
{
char code = (char)('a' + ch12v - 1);
solve(roq12, asf + code);
}
}
}
signed main()
{
string str;
cin >> str;
solve(str, "");
}
Subscribe to the newsletter so that you never miss any post or update just like this one.
You can follow me on Hashnode for:


