我正在解决需要解码字符串的问题..
A message containing letters from A-Z 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).
我想出了下面的递归方法,但它为输入“227”提供了错误的输出。输出应该是“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;
}
我上面的方法有什么问题吗?
最佳答案
在这一行中-
if (k >= 2 && Integer.parseInt(data.substring(0, 2)) <= 26) {
您始终检查相同的 2 位数字 data.substring(0, 2)
。相反,考虑类似的事情
data.substring(data.length()-k, data.length()).substring(0, 2)
或
data.substring(data.length()-k, data.length()-k+2)
关于java - 解码字符串有多少种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976434/