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.

这个题用动态规划的方法做。

cur记录目标数字,pre记录目标前一个数字。然后分类讨论,注意细节就行了。

代码如下:

public class Solution {
    public int numDecodings(String s) {
        int n=s.length();
        if(n==0||s.charAt(0)=='0')
            return 0;
        int[] nums=new int[n];
        nums[0]=1;
        for(int i=1;i<n;i++){
        	int cur=s.charAt(i)-'0';
        	int pre=s.charAt(i-1)-'0';
        	if(cur==0){
        		if(pre==1||pre==2){
        			nums[i]=i==1?1:nums[i-2];
        		}else{
        			nums[i]=0;
        		}
        	}else if(cur<=6&&cur>=1){
    			if(pre==2||pre==1){
    				nums[i]=i==1?2:nums[i-1]+nums[i-2];
    			}else{
    				nums[i]=nums[i-1];
    			}
    		}else{
    			if(pre==1){
    				nums[i]=i==1?2:nums[i-1]+nums[i-2];
    			}else{
    				nums[i]=nums[i-1];
    			}
        	}
        }
        return nums[n-1];
    }
}


你可能感兴趣的:(java,LeetCode,动态规划)