Decode Ways
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) {
int length = s.length();
int[] sum = new int[length];
if (s.equals(""))
return 0;
if (s.charAt(0) == '0')
sum[0] = 0;
else
sum[0] = 1;
if (length == 1)
return sum[length - 1];
if (sum[0] == 0) {
if (s.charAt(1) == '0')
sum[1] = 0;
} else {
if (s.charAt(1) == '0') {
if (Integer.parseInt(s.substring(0, 2)) < 27)
sum[1] = 1;
else
sum[1] = 0;
} else {
if (Integer.parseInt(s.substring(0, 2)) < 27)
sum[1] = 2;
else
sum[1] = 1;
}
}
if (length == 2)
return sum[length - 1];
for (int i = 2; i < length; i++) {
if (s.charAt(i - 1) == '0')
if (s.charAt(i) == '0') {
return 0;
}
if (s.charAt(i) != '0') {
if (Integer.parseInt(s.substring(i - 1, i + 1)) < 27)
if (s.charAt(i - 1) != '0')
sum[i] = sum[i - 1] + sum[i - 2];
else
sum[i] = sum[i - 1];
else
sum[i] = sum[i - 1];
} else {
if (Integer.parseInt(s.substring(i - 1, i + 1)) < 27)
sum[i] = sum[i - 2];
else
return 0;
}
}
return sum[length - 1];
}
}
public class Solution {
public int numDecodings(String s) {
int length = s.length();
int[] sum = new int[length];
if (s.equals(""))
return 0;
if (s.charAt(0) == '0')
sum[0] = 0;
else
sum[0] = 1;
if (length == 1)
return sum[length - 1];
if (sum[0] == 0) {
if (s.charAt(1) == '0')
sum[1] = 0;
} else {
if (s.charAt(1) == '0') {
if (Integer.parseInt(s.substring(0, 2)) < 27)
sum[1] = 1;
else
sum[1] = 0;
} else {
if (Integer.parseInt(s.substring(0, 2)) < 27)
sum[1] = 2;
else
sum[1] = 1;
}
}
if (length == 2)
return sum[length - 1];
for (int i = 2; i < length; i++) {
if (s.charAt(i - 1) == '0')
if (s.charAt(i) == '0') {
return 0;
}
if (s.charAt(i) != '0') {
if (Integer.parseInt(s.substring(i - 1, i + 1)) < 27)
if (s.charAt(i - 1) != '0')
sum[i] = sum[i - 1] + sum[i - 2];
else
sum[i] = sum[i - 1];
else
sum[i] = sum[i - 1];
} else {
if (Integer.parseInt(s.substring(i - 1, i + 1)) < 27)
sum[i] = sum[i - 2];
else
return 0;
}
}
return sum[length - 1];
}
}