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

标签 java algorithm data-structures

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

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/

相关文章:

java - 如何从JSP页面获取数据到servlet

java - JUnit 测试中的假设与断言

c++ - 查询问题优化

c - 链接列表创建 - 垃圾输出?

java - 将 Java 字符串转换为 Json

c - 排序算法未通过

algorithm - 术语 "VISITED"的 BFS 和正确性

java - 用于保存可互换字符串集的数据结构

c++ - 在二叉搜索树中插入值

java - 在 Access 中添加新记录