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:
int numDecodings(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int length = s.size(); if(length<1)return 0; int* dp = new int[length+1]; memset(dp, 0, sizeof(int)*(length+1)); dp[0] = 1; if(s[0] == '0')dp[1] = 0; else dp[1] = 1; for(int i = 2; i <= length; ++i) { int num = stoi(s.substr(i-1,1)); if(num > 0) dp[i] = dp[i-1]; num = stoi(s.substr(i-2,2)); if(num > 9 && num < 27) dp[i] += dp[i-2]; } int res = dp[length]; delete[] dp; return res; }
作者:doc_sgl 发表于2013-9-28 0:43:21 原文链接
阅读:179 评论:0 查看评论