Title:
A message containing letters from was A-Z
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 is "12"
2.
Test Instructions:
A-Z
A message containing letters is encoded into numbers:
' A '-1 ' B '-2 ... ' Z '-26
Given a coded message that contains numbers, it determines how many decoding methods are ultimately in common.
Like what:
give "12", It can be decoded into " AB "
  (12) or " L "
The final decoding method is 2.
Algorithm Analysis:
Reference Blog: http://blog.csdn.net/u011095253/article/details/9248109
* Sweep the string from beginning to end, for example, we want to know, from the first to Dp[i] this bit composed of string, there are a number of decoding combinations, then there are two cases
* First: If dp[i] corresponds to a single character that can be decoded, then Dp[i] includes the number of combinations accumulated by the former dp[i-1] bit dp[i] = dp[i-1]
* Second: If not only dp[i] the corresponding single character can decode, dp[i-1]-dp[i], two characters can also be decoded,
* So not only includes dp[i-1] accumulated number of combinations, also including dp[i-2] bit accumulation of combinations dp[i] = Dp[i-1] + dp[i-2]
* We built an array of n+1, for the sake of brevity, we put a 1 in front. So pay attention to the index in the index-1==string in the array.
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution {public int numdecodings (String s) { int n = s.length (); if (n==0) return 0; Int[] dp = new INT[N+1]; Dp[0] = 1; if (IsValid (s.substring (0,1))) dp[1] = 1; else dp[1] = 0; for (int i=2; i<=n;i++) { if (IsValid (s.substring (i-1,i))) dp[i] = dp[i-1]; if (IsValid (s.substring (i-2,i))) Dp[i] + = Dp[i-2]; } return dp[n]; } public Boolean isValid (String s) { if (s.charat (0) = = ' 0 ') return false; int code = Integer.parseint (s); return code>=1 && code<=26; }} </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Decode Ways