I am working on problem where I need to decode a string..
A message containing letters from AZ is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
I came up with below recursion approach but it is giving wrong output for this input "227". Output should be "2" but my program is giving "3":
public static int decodeWays(String data) {
return helper(data, data.length());
}
private static int helper(String data, int k) {
if (k == 0)
return 1;
int s = data.length() - k;
if (data.charAt(s) == '0')
return 0;
int result = helper(data, k - 1);
if (k >= 2 && Integer.parseInt(data.substring(0, 2)) <= 26) {
result += helper(data, k - 2);
}
return result;
}
What is wrong with my above approach?
In this line-
if (k >= 2 && Integer.parseInt(data.substring(0, 2)) <= 26) {
You always check the same 2-digit number data.substring(0, 2)
. Instead consider something like
data.substring(data.length()-k, data.length()).substring(0, 2)
or
data.substring(data.length()-k, data.length()-k+2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.