码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 91. Decode Ways

时间:2017-07-04 11:16:56      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:color   blog   ++   span   开始   div   public   logs   编码方式   

leetcode 91. 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.

考虑动态规划,从第二个字符开始,以第i个字符结尾的子字符串的编码方式为dp[i],如果第i个字符不能和第i-1个字符组成10-26之间的数,那么dp[i]=dp[i-1],否则加上dp[i-2]的值(即第i和第i-1的组成一个字符)。

 

public class Solution {
    public int numDecodings(String s) {
        int n=s.length();
        if (n==0) return 0;
        if (s.charAt(0)==‘0‘)return 0;
        int[] dp=new int[n+1];
        dp[0]=1;//没有字符时
        dp[1]=1;//有一个字符时
        for (int i=1;i<n;i++){
            if (s.charAt(i)>=‘1‘&&s.charAt(i)<=‘9‘){
                dp[i+1]=dp[i];
            }
            if (s.charAt(i)>=‘0‘&&s.charAt(i)<=‘6‘&&s.charAt(i-1)==‘2‘){
                dp[i+1]+=dp[i-1];
            }
            if (s.charAt(i)>=‘0‘&&s.charAt(i)<=‘9‘&&s.charAt(i-1)==‘1‘){
                dp[i+1]+=dp[i-1];
            }
        }
        return dp[n];
    }
}

 

leetcode 91. Decode Ways

标签:color   blog   ++   span   开始   div   public   logs   编码方式   

原文地址:http://www.cnblogs.com/sure0328/p/7115087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!