《剑指offer》第四十六题(把数字翻译成字符串)

时间:2021-12-10 21:19:35
// 面试题46:把数字翻译成字符串
// 题目:给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成"a",1翻
// 译成"b",……,11翻译成"l",……,25翻译成"z"。一个数字可能有多个翻译。例
// 如12258有5种不同的翻译,它们分别是"bccfi"、"bwfi"、"bczi"、"mcfi"和
// "mzi"。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。 #include <string>
#include <iostream> using namespace std; int GetTranslationCount(const string& number); int GetTranslationCount(int number)
{
if (number < )
return ; string numberInString = to_string(number);//转换成字符串
return GetTranslationCount(numberInString);
} int GetTranslationCount(const string& number)
{
int length = number.length();
int* counts = new int[length];
int count = ; for (int i = length - ; i >= ; --i)//从右开始计算,避免递归中碰到重复的子问题
{
count = ;
if (i < length - )
count = counts[i + ];
else
count = ; if (i < length - )
{
int digit1 = number[i] - '';
int digit2 = number[i + ] - '';
int converted = digit1 * + digit2;
if (converted >= && converted <= )//满足条件,记录当前位置所有可能的次数
{
if (i < length - )//有点动态规划的意思
count += counts[i + ];
else
count += ;
}
} counts[i] = count;
} count = counts[];//返回counts第一个值
delete[] counts; return count;
} // ====================测试代码====================
void Test(const string& testName, int number, int expected)
{
if (GetTranslationCount(number) == expected)
cout << testName << " passed." << endl;
else
cout << testName << " FAILED." << endl;
} void Test1()
{
int number = ;
int expected = ;
Test("Test1", number, expected);
} void Test2()
{
int number = ;
int expected = ;
Test("Test2", number, expected);
} void Test3()
{
int number = ;
int expected = ;
Test("Test3", number, expected);
} void Test4()
{
int number = ;
int expected = ;
Test("Test4", number, expected);
} void Test5()
{
int number = ;
int expected = ;
Test("Test5", number, expected);
} void Test6()
{
int number = ;
int expected = ;
Test("Test6", number, expected);
} void Test7()
{
int number = ;
int expected = ;
Test("Test7", number, expected);
} void Test8()
{
int number = ;
int expected = ;
Test("Test8", number, expected);
} void Test9()
{
int number = -;
int expected = ;
Test("Test9", number, expected);
} int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
system("pause");
return ;
}