数字字符串转换为字母组合的种数

【题目】给定一个字符串str,str全部由数组字符组成,如果str中某一个或某相邻两个字符组成的子串值在1~26之间,则这个子串可以转换为一个字母。规定“1”转换为“A",“2"转换为”B”,“3"转换为“C”…“26转换为”Z”.写一个函数,求str有多少种不同的转换结果,并返回种数。

public class NumToStr {
	// 暴力递归
	public static int num1(String str) {
		if (str == null || str.equals("")) {
			return 0;
		}
		char[] chas = str.toCharArray();
		return process(chas, 0);
	}

	public static int process(char[] chas, int i) {
		if (i == chas.length) {
			return 1;
		}
		if (chas[i] == '0') {
			return 0;
		}
		int res = process(chas, i + 1);
		if (i + 1 < chas.length && (chas[i] - '0') * 10 + chas[i + 1] - '0' < 27) {
			res += process(chas, i + 2);
		}
		return res;
	}

	// dp
	public static int num2(String str) {
		if (str == null || str.equals("")) {
			return 0;
		}
		char[] chas = str.toCharArray();
		int next = 1;
		int cur = chas[chas.length - 1] == '0' ? 0 : 1;
		int tmp = 0;
		for (int i = chas.length - 2; i >= 0; i--) {
			if (chas[i] == '0') {
				next = cur;
				cur = 0;
			} else {
				tmp = cur;
				if ((chas[i] - '0') * 10 + chas[i + 1] - '0' < 27) {
					cur += next;
				}
				cur = tmp;
			}
		}
		return cur;
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值