标签:
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()]; } }
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45066531