问题描述:
A message containing letters from A-Z is being encoded to numbers using the following
mapping:
A : 1
B : 2
. . .
Z : 26
Given an encoded message containing digits, determine the total number of ways to decode
it.
For example, given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).
The number of ways decoding “12” is 2.
解题思路:
因为每个字母的编码最长长度为2,因此我们可以一个数组就能进行遍历搜索。设所有的数字储存在数组data[0…length-1]中;count[i]储存从data[0…i]的decoding数目。
情况1:当data[i]的数值为0时,则只能有data[i-1,i]编码,此时count[i]=count[i-2];
情况2:当0<data[i]<10且(data[i-1,i]>26或data[i-1]==0),则count[i]=count[i-1];
情况3:当9<data[i-1,i]<26,则count[i]=count[i-1]+coun[i-2];
pseudo-code初始化{
count[0]=1;
if(data[1]==0||data[0,1]>26)
count[1]==1;
else
count[1]=2;
}//初始化结束;
for(i=2;i<data.length;i++)
{
if(data[i]==0)
count[i]=count[i-1];
else if( 0<data[i]<10 && ( data[i-1,i]>26||data[i-1]==0) )
count[i]=count[i-1];
else if(9<data[i-1,i]<26)
count[i]=count[i-1]+coun[i-2];
}//算法结束;
样例:
Sample: 1 1 2 3
i : 0 1 2 3
count[i]: 1 2 3 5
时间复杂度:算法进行了一次for循环,很明显时间复杂度为o(n).