[程序员代码面试指南]递归和动态规划-数字字符串转换为字母组合的种数(DP)

题意

给一个字符串,只由数字组成,若是'1'-'26',则认为可以转换为'a'-'z'对应的字母,问有多少种转换方法。

题解

状态转移很好想,注意dp多开一位,dp[0]为dp[2]的计算做准备。dp[i]表示到索引为i-1的字符(含)为止转换方法数。

代码

public class Main {
	public static void main(String args[]) {
		String str="01";
		System.out.print(transMeans(str));
	}
	
	public static int transMeans(String str) {
		if(str==null||str.length()==0) {
			return 0;
		}
		
		int[] dp=new int[str.length()+1];
		dp[0]=1;
		dp[1]=str.charAt(0)=='0'?0:1;		
		
		if(str.length()!=1) {
			for(int i=2;i<=str.length();++i) {
				dp[i]=dp[i-1]*isLetter(str.charAt(i-1))+dp[i-2]*isLetterWithTwoNum(str,i-1);
			}
		}		
		return dp[str.length()];
	}
	
	public static int isLetter(char c) {
		return c!='0'?1:0;
	}
	
	public static int isLetterWithTwoNum(String s,int i) {
		int num=(s.charAt(i-1)-'0')*10+s.charAt(i)-'0';
		return num>=1&&num<=26&&s.charAt(i-1)!='0'?1:0;
	}
}

posted on   coding_gaga  阅读(580)  评论(0编辑  收藏  举报

编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示