NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
**一. 题目描述** 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. **二. 题目分析** 题目的大意是,给你一串数字,解码成相应的英文字母。类似爬楼梯问题Climbing Stairs,可使用动态规划来完成。 **三. 示例代码** ~~~ #include <iostream> #include <string> using namespace std; class Solution { public: int numDecodings(const string &s) { if (s.empty() || s[0] == '0') return 0; int prev = 0; int cur = 1; // 长度为 n 的字符串,有 n+1 个阶梯 for (size_t i = 1; i <= s.size(); ++i) { if (s[i-1] == '0') cur = 0; if (i < 2 || !(s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) prev = 0; int tmp = cur; cur = prev + cur; prev = tmp; } return cur; } }; ~~~