zoukankan      html  css  js  c++  java
  • Decode Ways,编码方式数量求解。动态规划问题。

    问题描述:

    A message containing letters from A-Z is being encoded to numbers using the following mapping:

    'A' -> 1
    'B' -> 2
    ...
    'Z' -> 26
    

    Given an encoded message containing digits, determine the total number of ways to decode it.

    For example,
    Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

    The number of ways decoding "12" is 2.

    算法分析:题意解析:给你一串数字,解码成英文字母。
    类似爬楼梯问题,但要加很多限制条件。
    定义数组number,number[i]意味着:字符串s[0..i-1]可以有number[i]种解码方法。
    回想爬楼梯问题一样,number[i] = number[i-1] + number[i-2]
    但不同的是本题有多种限制:
    第一: s[i-1]不能是0,如果s[i-1]是0的话,number[i]就只能等于number[i-2]
    第二,s[i-2,i-1]中的第一个字符不能是0,而且Integer.parseInt(s.substring(i-2,i))获得的整数必须在0到26之间。

    public class DecodeWays 
    {
    	public int numDecodings(String s) 
    	{
    		if(s == null || s.length() == 0)
    		{
    			return  0;
    		}
    		if(s.charAt(0) == '0') 
    		{
    			return 0;
    		}
    		//dp[i]代表前i个字符有多少种编码方式
    		int[] dp = new int[s.length()+1];
    		dp[0] = 1;//必须初始化为1,例如字符串“10”,初始0出错。
    		dp[1] = 1;
    		for(int i = 2; i <= s.length(); i ++)
    		{
    			if(s.charAt(i-1) != '0')
    			{
    				dp[i] = dp[i-1];
    			}
    			if(s.charAt(i-2) != '0')
    			{
    				int temp = Integer.parseInt(s.substring(i-2, i));
    				if(temp >0 && temp <= 26)
    				{
    					dp[i] += dp[i-2];
    				}
    			}
    		}
    		return dp[s.length()];
        }
    }
    
  • 相关阅读:
    react 常用组件整理
    react 问题记录二(侧重于state或者说server层操作)
    web前端常用小函数汇总
    vue 路由跳转四种方式 (带参数) 【转藏】
    微信小程序实用组件:省市区三级联动
    vue table组件显示一个图片

    520
    微信小程序,子页面调用父页面的函数和方法
    webstorm 右侧滚动条怎么设置颜色
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5822507.html
Copyright © 2011-2022 走看看