剑指Offer——面试题46:把数字翻译成字符串

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

#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<cmath>
using namespace std;
/**
 * 递归从最大的问题开始自上而下解决问题,但由于存在重复的子问题,
 * 我们也可以从最小的子问题开始自上而上解决问题, 这样就可以消除重复的子问题。 
 **/
int GetTranslationCount(const string& number){
	int len=number.length();
	int* counts=new int[len];
	int count=0;
	for(int i=len-1;i>=0;i--){
		count=0;
		if(i<len-1) count=counts[i+1];
		else count=1;
		
		if(i<len-1){
			int digit1=number[i]-'0';
			int digit2=number[i+1]-'0';
			int combineNum=digit1*10+digit2;
			if(combineNum>=10 && combineNum<=25){
				if(i<len-2) count+=counts[i+2]; 
				else count++;
			}
		}
		counts[i]=count;
	} 
	count=counts[0];
	delete[] counts;
	return count;
}
int GetTranslationCount(int number){
	if(number<0) return 0;
	string numberInString=to_string(number);
	return GetTranslationCount(numberInString);
}
int main() {
	printf("%d", GetTranslationCount(12258));
	return 0;
}
发布了49 篇原创文章 · 获赞 50 · 访问量 2440

猜你喜欢

转载自blog.csdn.net/qq_35340189/article/details/104455796
今日推荐