《剑指offer》第四十六题:把数字翻译成字符串
// 面试题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 < 0) return 0; string numberInString = to_string(number); //转为字符串 return GetTranslationCount(numberInString); } // f(i) = f(i + 1) + g(i, i+1) * f(i + 2) 递归思想 int GetTranslationCount(const string& number) { int length = number.length(); int* counts = new int[length]; //记录每一位的可能翻译次数 int count = 0; //临时变量 for (int i = length - 1; i >= 0; --i) //从最后一位开始往前计算 { count = 0; //记得清零临时变量 if (i < length - 1) //计算 f(i + 1) 部分 count = counts[i + 1]; else count = 1; if (i < length - 1) //计算 g(i, i+1) * f(i + 2) 部分 { int num1 = number[i] - '0'; int num2 = number[i + 1] - '0'; int converted = num1 * 10 + num2; if (converted <= 25 && converted >= 10) //g(i, i+1) { if (i < length - 2) count += counts[i + 2]; else count += 1; } } counts[i] = count; //更新当前位可能翻译数 } count = counts[0]; 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 = 0; int expected = 1; Test("Test1", number, expected); } void Test2() { int number = 10; int expected = 2; Test("Test2", number, expected); } void Test3() { int number = 125; int expected = 3; Test("Test3", number, expected); } void Test4() { int number = 126; int expected = 2; Test("Test4", number, expected); } void Test5() { int number = 426; int expected = 1; Test("Test5", number, expected); } void Test6() { int number = 100; int expected = 2; Test("Test6", number, expected); } void Test7() { int number = 101; int expected = 2; Test("Test7", number, expected); } void Test8() { int number = 12258; int expected = 5; Test("Test8", number, expected); } void Test9() { int number = -100; int expected = 0; Test("Test9", number, expected); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); Test9(); return 0; }
分析:有点像斐波那契数,不过加了个判断。