|
| 1 | +/** |
| 2 | + * @param {string} s |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | + |
| 6 | +// TLE |
| 7 | +// var numDecodings = function(s) { |
| 8 | +// const codeMap = {}; |
| 9 | +// for (let i = 1; i <= 26; i++) { |
| 10 | +// codeMap[i] = String.fromCharCode(64 + i); |
| 11 | +// } |
| 12 | + |
| 13 | +// const memo = {}; |
| 14 | +// let count = 0; |
| 15 | +// function go(string, start) { |
| 16 | +// if (start >= string.length) { |
| 17 | +// count++; |
| 18 | +// return; |
| 19 | +// } |
| 20 | + |
| 21 | +// const firstDigit = string[start]; |
| 22 | +// const secondDigit = string[start + 1]; |
| 23 | +// if (firstDigit === "0") return; |
| 24 | + |
| 25 | +// if (codeMap[firstDigit]) { |
| 26 | +// go(string, start + 1); |
| 27 | +// } |
| 28 | + |
| 29 | +// const twoDigits = firstDigit + secondDigit; |
| 30 | +// if (Number(twoDigits) <= 26 && codeMap[twoDigits]) { |
| 31 | +// go(string, start + 2); |
| 32 | +// } |
| 33 | +// } |
| 34 | + |
| 35 | +// go(s, 0, ""); |
| 36 | + |
| 37 | +// return count; |
| 38 | +// }; |
| 39 | + |
| 40 | +// TC: O(n) -> string 길이만큼 |
| 41 | +// SC: O(n) -> string 길이만큼 스택 생성 |
| 42 | +var numDecodings = function (s) { |
| 43 | + const codeMap = {}; |
| 44 | + for (let i = 1; i <= 26; i++) { |
| 45 | + codeMap[i] = String.fromCharCode(64 + i); |
| 46 | + } |
| 47 | + |
| 48 | + const memo = {}; |
| 49 | + |
| 50 | + function go(start) { |
| 51 | + if (start >= s.length) return 1; |
| 52 | + if (memo[start] !== undefined) return memo[start]; |
| 53 | + |
| 54 | + const firstDigit = s[start]; |
| 55 | + const secondDigit = s[start + 1]; |
| 56 | + |
| 57 | + if (firstDigit === '0') return 0; |
| 58 | + |
| 59 | + let ways = 0; |
| 60 | + |
| 61 | + if (codeMap[firstDigit]) { |
| 62 | + ways += go(start + 1); |
| 63 | + } |
| 64 | + |
| 65 | + const twoDigits = firstDigit + secondDigit; |
| 66 | + if (Number(twoDigits) <= 26 && codeMap[twoDigits]) { |
| 67 | + ways += go(start + 2); |
| 68 | + } |
| 69 | + |
| 70 | + memo[start] = ways; |
| 71 | + |
| 72 | + return ways; |
| 73 | + } |
| 74 | + |
| 75 | + return go(0); |
| 76 | +}; |
0 commit comments