题解 | #把数字翻译成字符串#
把数字翻译成字符串
https://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668
递归的关键在于要排除掉非法的字符串,如 带"00"或者"0"开头的字符串
class Solution { public: /** * 解码 * @param nums string字符串 数字串 * @return int整型 */ int solve(string nums) { int n = nums.size(); if(n == 1 && nums[0] == '0') return 0; vector<int> dp(n, 0); dp[0] = 1; for(int i = 1; i < n; i++) { if(nums[i] != '0') dp[i] = dp[i - 1]; int tmp = 10 * (nums[i - 1] -'0') + nums[i] - '0'; if(tmp >= 10 && tmp <= 26) { if(i == 1) ++dp[i]; else dp[i] += dp[i-2]; } } return dp[n-1]; } };