首页 > 其他 > 详细

leetcode 91. Decode Ways

时间:2017-07-04 10:52:44      阅读:214      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!