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.
===================================================================
题目链接:https://leetcode.com/problems/decode-ways/
题目大意:求一共有多少种解码方式,其中解码规则是:‘A'对应1,‘B’对应2,……,‘Z’对应26。
思路:动态规划,新建一个长度为n+1的数组dp,其中dp[0]=1,dp[i]表示s前面i个字符的解码方式。
1、当是s[i]=='0'时,如果前面一个数字不存在或者不是1、2,则直接返回0,否则dp[i+1]=dp[i-1]。
2、i>0且当s[i-1]=='1'时或者s[i-1]==2且s[i]>='1',s[i]<='6'时,dp[i+1] = dp[i] + dp[i-1]。
3、其他情况下,dp[i+1] = dp[i] 。
参考代码:
class Solution {
public:
int numDecodings(string s) {
int n = s.size() ;
if ( n == 0 )
return 0 ;
vector <int> dp ( n + 1 , 0 ) ;
dp[0] = 1 ;
for ( int i = 0 ; i < n ; i ++ )
{
if ( s[i] == '0' )
{
if ( i == 0 || ! ( s[i-1] >= '1' && s[i-1] <= '2' ) )
return 0 ;
dp[i+1] = dp[i-1] ;
}
else if ( i && ( s[i-1] == '1' || ( s[i] >= '1' && s[i] <= '6' && s[i-1] == '2' ) ) )
dp[i+1] = dp[i] + dp[i-1] ;
else
dp[i+1] = dp[i] ;
}
return dp[n] ;
}
};