[LeetCode] Decode Ways

来源:互联网 发布:网络空间用什么来描绘 编辑:程序博客网 时间:2024/05/16 19:09

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.

动态规划,讨论清楚情况即可:

public class Solution {    public int numDecodings(String s) { if(s.length()==0) return 0; int[] dp=new int[s.length()+1]; dp[0]=1; for(int i=0;i<s.length();i++){ char ch=s.charAt(i); if(i==0){ if(ch=='0') return 0; dp[i+1]=1; }else{ boolean re=canCombine(s.charAt(i-1), ch); if(ch=='0'&&re) dp[i+1]=dp[i-1]; else if(ch=='0'&&!re) return 0; else if(ch!=0&&re) dp[i+1]=dp[i-1]+dp[i]; else dp[i+1]=dp[i]; } } return dp[dp.length-1]; } public boolean canCombine(char a,char b){ if(a=='1') return true; else if(a=='2') return b<='6'; else return false; }}