首页 > 其他 > 详细

LeetCode Decode Ways

时间:2015-04-15 23:20:55      阅读:220      评论:0      收藏:0      [点我收藏+]

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.

题意:求一串字符串的所有可能。

思路:DP,设dp[i]表示长度为i时的可能,那么dp[i] = dp[i-1],如果s[i-1]非零的话;同理只要s[i-2]!=‘0‘且在[1,26]的话,那么这个两位数也是一种可能,所以dp[i]+=dp[i-2].

public class Solution {
    public int numDecodings(String s) {
    	if (s == null || s.length() == 0) return 0;
    	if (s.charAt(0) == '0') return 0;
    	
    	int dp[] = new int[s.length()+1];
    	dp[0] = 1;
    	dp[1] = 1;
    	for (int i = 2; i <= s.length(); i++) {
    		int tmp = Integer.parseInt(s.substring(i-1, i));
    		if (tmp != 0) dp[i] = dp[i-1];
    		if (s.charAt(i-2) != '0') {
    			tmp = Integer.parseInt(s.substring(i-2, i));
    			if (tmp >= 1 && tmp <= 26) 
    				dp[i] += dp[i-2];
    		}
    	}
    	
    	return dp[s.length()];
    }
}



LeetCode Decode Ways

原文:http://blog.csdn.net/u011345136/article/details/45066531

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