将数字解码为字母可能的解码方法,a-z 分别表示 1-26
动态规划求解
- Runtime: 72 ms, faster than 96.23%
- Memory Usage: 37.2 MB, less than 73.14%
dp[i] = dp[i - 1] + dp[i - 2]; 10~26 当前位置不为0
dp[i] = dp[i - 1];
dp[i] = dp[i - 2]; 0~26 当前位置为0
return 0 ;第一位为0 > 26
var numDecodings = function(s) {
let len = s.length
if(len === 0 || s[0] === '0') return 0
let dp = [1]
for(let i = 1; i < len; i++) {
let cur = s.substr(i - 1, 2) - '0'
if(cur === 10 || cur === 20) {
dp[i] = i === 1 ? 1 : dp[i - 2]
} else if(cur > 26 || cur <= 9) {
if(cur <= 9 && i === 1 || cur % 10 === 0) return 0
dp[i] = dp[i - 1]
} else {
dp[i] = i === 1 ? 2 : (dp[i - 1] + dp[i - 2])
}
}
return dp[len - 1]
};
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function(s) {
if(s[0] === '0') return 0
let len = s.length
let dp = new Array(len)
dp[0] = 1
for (let i = 1; i < len; i++) {
let prev = s[i]
let cur = s.substr(i - 1, 2) - '0'
if (prev !== '0' && cur >= 10 && cur <= 26) { //如15 22 dp[i] = dp[i - 1] + dp[i - 2]
dp[i] = i === 1 ? 2 : dp[i - 1] + dp[i - 2]
} else if(prev === '0' && cur >= 10 && cur <= 26) {//如 10 20 dp = dp[i - 2]
dp[i] = i === 1 ? 1 : dp[i - 2]
} else if (prev === '0' && (cur > 26 || cur === 0)) { //如 00 30 40 return 0
return 0
} else {
dp[i] = dp[i - 1]
}
}
return dp[len - 1]
};