首页 > 试题广场 >

解码

[编程题]解码
  • 热度指数:4253 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解

有一种将字母编码成数字的方式:'a'->1, 'b->2', ... , 'z->26'。

现在给一串数字,给出有多少种可能的译码结果。




输入描述:
编码后数字串


输出描述:
可能的译码结果数
示例1

输入

12

输出

2

说明

2种可能的译码结果(”ab” 或”l”)
示例2

输入

31717126241541717

输出

192

说明

192种可能的译码结果
import java.util.Scanner;

public class Main {
    public static int process(char[] ch, int i) {
        if (i == ch.length) {
            return 1;
        }
        if (ch[i] == '0') {
            return 0;
        }
        if (ch[i] == '1') {
            int res = process(ch, i + 1);
            if (i + 1 < ch.length) {
                res += process(ch, i + 2);
            }
            return res;
        }
        if (ch[i] == '2') {
            int res = process(ch, i + 1);
            if (i + 1 < ch.length && ch[i] >= '0' && ch[i + 1] <= '6') {
                res += process(ch, i + 2);
            }
            return res;
        }
        return process(ch, i + 1);
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        if (str.length() < 1) {
            System.out.println(0);
        } else {
            System.out.println(process(str.toCharArray(), 0));
        }
    }
}
发表于 2019-06-12 22:44:19 回复(0)