gpt4 book ai didi

java - 解码字符串的方法有多少?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:03 25 4
gpt4 key购买 nike

我正在处理需要解码字符串的问题..

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com