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.
public class Solution {
public int numDecodings(String s) {
if (s == null || s.length() == 0) return 0;
if (s.length() == 1) {
if (s.equals("0")) {
return 0;
} else {
return 1;
}
}
if (s.length() == 2) {
if (s.charAt(0) == '0') return 0;
int value = Integer.parseInt(s);
if (value == 10 || value == 20) return 1;
if (value <= 26) return 2;
if (value % 10 == 0) return 0;
return 1;
}
int preV = numDecodings(s.substring(0, 2)) > 0 ? 1 : 0;
return numDecodings(s.substring(0, 1)) * numDecodings(s.substring(1, s.length())) + preV * numDecodings(s.substring(2, s.length()));
}
}
Another version:
public class Solution {
public int numDecodings(String s) {
if (s.length() == 0) return 0;
int len = s.length();
if (len < 1) return 0;
int[] numarray = new int[len];
int i = len - 1;
numarray[i] = (s.charAt(i) == '0') ? 0 : 1;
i--;
while (i >= 0) {
if (s.charAt(i) == '0') numarray[i] = 0;
else if (s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i+1) <= '6'))
if (i == len - 2) {
numarray[i] = numarray[i+1] + 1;
} else {
numarray[i] = numarray[i+1] + numarray[i+2];
}
else
numarray[i] = numarray[i+1];
i--;
}
return numarray[0];
}
}