面试题46:把数字翻译成字符串。给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成“a”,1翻译成“b”,…,25翻译成“z”。一个数字可能有多个翻译,如,12258有5种不同翻译,分别是“bccfi”、“bwfi”、“bczi”、“mcfi”和“mzi”,编程实现一个函数,计算一个数字有多少种不同的翻译方法。
我们以12258为例分析,我们有两种选择来翻译第一位数字1,第一种是翻译为“b”,剩下2258,第二种是1和后面的2一起翻译为“m”,剩下258。当最开始的一个或两个数字被翻译成一个字符后,我们接着翻译后面剩下的数字,我们可以用一个递归来完成计算。
定义函数f(i)为从第i位数字开始的不同的翻译数目,那么f(i)=f(i+1)+g(i,i+1)xf(i+2),当第i位和第i+1位拼接起来的数字在10~25的范围内时,函数g(i,i+1)的值为1,否则为0。
尽管递归可以解决这个问题,但由于存在重复的子问题,最好的方法是从小问题开始自底向上解决问题:
#include <iostream>
#include <string>
using namespace std;
int GetTranslationCount(const string& numString) {
int length = numString.size();
int count = 0;
int* counts = new int[length]; // 运行时才知道数组大小,需要用到堆内存
for (int i = length - 1; i >= 0; --i) {
count = 0;
if (i == length - 1) {
count = 1;
} else {
count = counts[i + 1];
int firstDigit = numString[i] - '0';
int secondDigit = numString[i + 1] - '0';
int covert = firstDigit * 10 + secondDigit;
if (covert <= 25 && covert >= 10) {
if (i < length - 2) { // 如果i为倒数第三位及以后的数字
count += counts[i + 2];
} else { // 若为第二位
count += 1;
}
}
}
counts[i] = count;
}
count = counts[0];
delete[] counts;
return count;
}
int GetTranslationCount(int num) {
if (num < 0) { // 输入数字应为正数
return 0;
}
string numString = to_string(num);
return GetTranslationCount(numString);
}
int main() {
cout << GetTranslationCount(12258) << endl;
}