Topic: Given a number, we translate it into a string according to the following rules: 0 is translated into "a", 1 is translated into "b", ..., 25 is translated into "z". There may be multiple translations for a number. Please implement a function to calculate how many different translation methods a number has.
def digit_to_string(num):
num = str(num)
length = len(num)
res = [0]*length
i=length-1
while i>=0:
if i==length-1:
res[i]=1
elif i==length-2:
if int(num[i:])<26:
res[i]=2
else:
res[i]=1
else:
if int(num[i:i+2]) < 26:
res[i]=res[i+1] + res[i+2]
else:
res[i]=res[i+1]
i-=1
return res[0]
Note: Use the idea of dynamic programming. f[i]=f[i+1]+g[i,i+1]f[i+2], g[i,i+1] is whether the number composed of i, i+1 is less than 26, If it is less than, it can be split into two, g[i,i+1] is 1, if it is greater than or equal to 26, it cannot be split, and g[i,i+1] is 0.