把数字翻译成字符串python_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
count+=counts[i+1]
else:
count=1
if i
digit1=int(numberStr[i])
digit2=int(numberStr[i+1])
converted=digit1*10+digit2
if converted>=10 and converted<=25:
if i
count+=counts[i+2]
else:
count+=1
counts[i]=count
return counts[0]
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的把数字翻译成字符串python_46 把数字翻译成字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python自动化工具_Python啥都
- 下一篇: python常用编译器和解释器的区别_P