题目:
给定一个数字,我们按照如下规则把它翻译为字符串:
0翻译成”a”,1翻译成”b”,……,11翻译成”l”,……,25翻译成”z”。一个数字可能有多个翻译。例如12258有5种不同的翻译,它们分别是”bccfi”、”bwfi”、”bczi”、”mcfi”和”mzi”。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。
解答:
class Solution:
def getTranslationCount(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
self.d = {}
return self.count(s)
def count(self, s):
if len(s) <= 1:
if s not in self.d:
self.d[s] = 1
return 1
else:
if 10 <= int(s[0])*10 + int(s[1]) <= 25:
n = self.d.get(s[1:],self.count(s[1:])) + self.d.get(s[2:], self.count(s[2:]))
if s not in self.d:
self.d[s] = n
return n
else:
n = self.d.get(s[1:],self.count(s[1:]))
if s not in self.d:
self.d[s] = n
return n
class Solution {
public:
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;
}
};