Skip to content

Instantly share code, notes, and snippets.

@sturgle
Last active January 1, 2016 10:29
Show Gist options
  • Save sturgle/8131897 to your computer and use it in GitHub Desktop.
Save sturgle/8131897 to your computer and use it in GitHub Desktop.
/*
http://www.careercup.com/question?id=19300678
If a=1, b=2, c=3,....z=26. Given a string, find all possible codes that string can generate. Give a count as well as print the strings.
For example:
Input: "1123". You need to general all valid alphabet codes from this string.
Output List
aabc //a = 1, a = 1, b = 2, c = 3
kbc // since k is 11, b = 2, c= 3
alc // a = 1, l = 12, c = 3
aaw // a= 1, a =1, w= 23
kw // k = 11, w = 23
*/
#include <vector>
#include <iostream>
#include <string>
using namespace std;
void helper(const string &num, int idx, string &tmp, int &count)
{
if (idx == num.length())
{
count++;
cout << tmp << endl;
}
else
{
if ((num[idx] == '1' && (idx + 1) != num.length())
|| (num[idx] == '2' && (idx + 1) != num.length() && num[idx + 1] <= '6'))
{
char c = (char)((num[idx] - '0') * 10 + num[idx + 1] - '0' + 'a' - 1);
string tmp1 = tmp + c;
helper(num, idx + 2, tmp1, count);
}
char c = (char)(num[idx] - '0' + 'a' - 1);
string tmp2 = tmp + c;
helper(num, idx + 1, tmp2, count);
}
}
// return the count
int convertAndCount(const string &num)
{
string result;
int count = 0;
helper(num, 0, result, count);
return count;
}
int main()
{
int count = convertAndCount("1123");
cout << count << en);
return 0;
}
@sturgle
Copy link
Author

sturgle commented Dec 26, 2013

use decode() instead of convert()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment