题目:
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.
Solution:
class Solution {
String s;
public int numDecodings(String s) {
this.s = s;
if(s == null || s.length() == 0) {
return 0;
}
int n = s.length();
int[] f = new int[n];
if(s.charAt(0) != '0') {
f[0] = 1;
} else {
f[0] = 0;
return 0;
}
if(s.length() == 1) {
return f[0];
}
for(int i = 1; i < n; i++) {
int a = single(i);
int b = isOrNo(i - 1, i);
if(i >= 2) {
f[i] = f[i - 1] * a + f[i - 2] * b;
} else {
f[i] = f[i - 1] * a + b;
}
if(a == 0 && b == 0) {
return 0;
}
}
return f[n - 1];
}
private int single(int i) {
if(s.charAt(i) != '0') {
return 1;
} else {
return 0;
}
}
private int isOrNo(int l, int r) {
int nl = s.charAt(l) - '0';
int nr = s.charAt(r) - '0';
int sum = nl * 10 + nr;
if(nl == 0) {
return 0;
}
if(sum <= 26 && sum >= 1) {
return 1;
} else {
return 0;
}
}
}