标签:style blog color io for re c 问题
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问题。
对于s中位置i(s[i] != ‘0‘)上的字符,有两种可能:
代码如下:
1 public class Solution { 2 private boolean isValidNum(String s,int i){ 3 if(i <= 0) 4 return false; 5 int first = s.charAt(i-1)-‘0‘; 6 int second = s.charAt(i)-‘0‘; 7 int num = first*10 + second; 8 if(num >= 10 && num <= 26) 9 return true; 10 return false; 11 } 12 public int numDecodings(String s) { 13 if(s==null || s.length() == 0) 14 return 0; 15 int length = s.length(); 16 int[] dp = new int[length+1]; 17 18 dp[0] = 1; 19 dp[1] = s.charAt(0) == ‘0‘?0:1; 20 21 for(int i=2;i<=length;i++){ 22 if(s.charAt(i-1) != ‘0‘) 23 dp[i]=dp[i-1]; 24 25 if(isValidNum(s, i-1)) 26 dp[i] += dp[i-2]; 27 } 28 return dp[length]; 29 } 30 }
【leetcode刷题笔记】Decode Ways,布布扣,bubuko.com
标签:style blog color io for re c 问题
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3865991.html