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解决
1 class Solution { 2 private: 3 vector<int> f; 4 public: 5 int getF(int index) 6 { 7 if (index < 0) 8 return 1; 9 else 10 return f[index]; 11 } 12 13 int numDecodings(string s) { 14 // Start typing your C/C++ solution below 15 // DO NOT write int main() function 16 if (s.size() == 0) 17 return 0; 18 19 f.resize(s.size()); 20 21 for(int i = 0; i < s.size(); i++) 22 { 23 f[i] = 0; 24 if (i >= 1) 25 { 26 string a(s, i - 1, 2); 27 if ("10" <= a && a <= "26") 28 f[i] += getF(i-2); 29 if ('1' <= s[i] && s[i] <= '9') 30 f[i] += getF(i-1); 31 } 32 else 33 { 34 if ('1' <= s[i] && s[i] <= '9') 35 f[i] = 1; 36 } 37 } 38 39 return f[f.size() - 1]; 40 } 41 };
本文深入探讨了如何使用动态规划解决字符串解码问题,具体阐述了解码算法的核心思想、实现步骤及实例分析。通过具体示例,展示了如何计算给定编码消息的所有可能解码方式,为理解字符串编码与解码提供了实用的解决方案。
1140

被折叠的 条评论
为什么被折叠?



