【剑指】46.把数字翻译成字符串

题目描述

  • 给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成"a",1翻译成"b",……,11翻译成"l",……,25翻译成"z"。一个数字可能有多个翻译。例如12258有5种不同的翻译,它们分别是"bccfi"、"bwfi"、"bczi"、"mcfi"和"mzi"。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。

算法分析

  • 自下而上,动态规划,从最小的问题开始 :
    f(r)表示以r为开始(r最小取0)到最右端所组成的数字能够翻译成字符串的种数。对于长度为n的数字,f(n)=0,f(n-1)=1,求f(0)。
    递推公式为 f(r-2) = f(r-1)+g(r-2,r-1)*f(r);
    其中,如果r-2,r-1能够翻译成字符,则g(r-2,r-1)=1,否则为0。
    因此,对于12258:
    f(5) = 0
    f(4) = 1
    f(3) = f(4)+0 = 1
    f(2) = f(3)+f(4) = 2
    f(1) = f(2)+f(3) = 3 
    f(0) = f(1)+f(2) = 5

提交代码:

class Solution {
public:
	int GetTranslationCount(int number) {
		if (number < 0)
			return 0;

		string num = to_string(number);
		return GetTranslationCountCore(num);
	}

	int GetTranslationCountCore(const string &number) {
		int count = 0;
		vector counts(number.size(), 0);
		int length = counts.size();

		/* 从后向前计算 */
		for (int i = length - 1; i >= 0; --i)
		{
			/* 当前字符单字符翻译 */
			if (i < length - 1)
				count = counts[i + 1];
			else
				count = 1;

			if (i < length - 1)
			{
				int digit1 = number[i] - '0';
				int digit2 = number[i + 1] - '0';
				int value = 10 * digit1 + digit2;
				if (value >= 10 && value <= 25)
				{
					if (i < length - 2)
						/* 当前字符与下一字符翻译 */
						count += counts[i + 2];
					else
						++count;
				}
			}
			counts[i] = count;
		}

		return counts[0];
	}

};

测试代码:

// ====================测试代码====================
void Test(const string& testName, int number, int expected)
{
	Solution s;
	if (s.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;
}

你可能感兴趣的:(剑指offer)