[英]number of ways to decode a string?
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:
使用以下映射将包含来自 AZ 的字母的消息编码为数字:
'A' -> 1
'A' -> 1
'B' -> 2
'B' -> 2
...
...
'Z' -> 26
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
给定一个只包含数字的非空字符串,确定解码它的方法总数。
Example 1:
示例 1:
Input: "12"
输入:“12”
Output: 2
输出:2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
说明:可以解码为“AB”(1 2)或“L”(12)。
Example 2:
示例 2:
Input: "226"
输入:“226”
Output: 3
输出:3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
解释:可以解码为“BZ”(2 26)、“VF”(22 6)或“BBF”(2 2 6)。
I came up with below recursion approach but it is giving wrong output for this input "227".我想出了下面的递归方法,但它为这个输入“227”提供了错误的输出。 Output should be "2" but my program is giving "3":
输出应为“2”,但我的程序给出“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)
.您始终检查相同的 2 位数字
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.