题解 | 把数字翻译成字符串
把数字翻译成字符串
https://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668
#include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 解码 * @param nums string字符串 数字串 * @return int整型 */ bool getlast(int pos, string nums){ int ans = (int)(nums[pos-1]-'0'); ans = ans*10 + (int)(nums[pos]-'0'); if(ans>=10&&ans<=26) return true; return false; } int solve(string nums) { // write code here if(nums.empty()) return 0; int len = nums.length(); vector<int> dp(len, 0); if(nums[0]!='0') dp[0] = 1; if(len==1) return dp[0]; if(nums[1]!='0') dp[1] = dp[0]; if(getlast(1, nums)) ++dp[1]; for(int i = 2; i < len; ++i){ if(getlast(i, nums)) dp[i] += dp[i-2]; if(nums[i]!='0') dp[i] += dp[i-1]; } return dp[len-1]; } };
dp,分成组合的前序和直接的前序,两者都有可能无法达成。
直接要求在1到9之间。
组合要求在10到26之间,09之类会产生错误,要注意。
如果初始只有一位的时候要及时返回,避免越界访问dp[1]。