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.
思路:斐波那契Fibonacci
类似与爬楼梯的题目,number[i] = number[i-1] + number[i-2],但要加很多限制条件。
第一: s[i-1]不能是0,只有s[i-1]不是0,number[i]才能加上number[i-1]
第二,s[i-2,i]中获得的整数必须在10到26之间,number[i]才能加上number[i-2]
public int numDecodings1(String s) {
int n0 = 1;//前i-2位共有多少编码方式
int n1 = 1;//前i-1位共有多少编码方式
if (s.length() == 0 || s.charAt(0) == '0') return 0;
for (int i = 2; i <= s.length(); i++) {
int n = 0; //前i位共有多少个编码方式.
if (s.charAt(i - 1) != '0') n = n1; //如果前一位不是0,+n1
int num = Integer.parseInt(s.substring(i - 2, i));
if (num >= 10 && num <= 26) n += n0;//如果前两位介于10到26,可以两位缩成1位编码,+n0即可.
n0 = n1;
n1 = n;
}
return n1;
}
爬楼梯的连接
http://blog.youkuaiyun.com/niuooniuoo/article/details/50949415