46 把数字翻译成字符串
题目
给定一个数字,按照如下规则翻译成字符串:0翻译成“a”,1翻译成“b”...25翻译成“z”。一个数字有多种翻译可能,例如12258一共有5种,分别是bccfi,bwfi,bczi,mcfi,mzi。实现一个函数,用来计算一个数字有多少种不同的翻译方法。
C++题解
以12258为例,从最大的问题开始,递归 :
递推公式: 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
int GetTranslationCount(const string& number);
int GetTranslationCount(int number)
{
if (number < 0)
return 0;
string numberInString = to_string(number);
return GetTranslationCount(numberInString);
}
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)
count = counts[i + 1];
else
count = 1;
if (i < length - 1)
{
//求出临近的两位数
int digit1 = number[i] - '0';
int digit2 = number[i + 1] - '0';
int converted = digit1 * 10 + digit2;
if (converted >= 10 && converted <= 25)
{
if (i < length - 2)
count += counts[i + 2];
else
count += 1;
}
}
counts[i] = count;
}
count = counts[0];
delete[] counts;
return count;
}
python 题解
class Solution:
def getTranslationCount(self, number):
"""
:type number: int
:rtype: int
"""
if number<0:
return 0
numberStr=str(number)
return self.getTranslateCount(numberStr)
def getTranslateCount(self,numberStr):
length=len(numberStr)
counts=[0]*length
#count=0
for i in range(length-1,-1,-1):
count=0
if i <length-1:
count+=counts[i+1]
else:
count=1
if i<length-1:
digit1=int(numberStr[i])
digit2=int(numberStr[i+1])
converted=digit1*10+digit2
if converted>=10 and converted<=25:
if i<length-2:
count+=counts[i+2]
else:
count+=1
counts[i]=count
return counts[0]