Created
April 11, 2023 15:46
-
-
Save hh54188/a469060f3aa12ac498b06dea5d9001a9 to your computer and use it in GitHub Desktop.
Decode ways algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var numDecodings = function (s) { | |
const availableNumStr = {}; | |
const cache = {} | |
let i = 1; | |
// 首先标记哪些数字可以解码为字母 | |
while (i < 27) { | |
availableNumStr[i.toString()] = true; | |
i++; | |
} | |
function decodeWays(s, count) { | |
// 在计算前首先检查是否存在缓存 | |
if (cache[s]) { | |
return cache[s]; | |
} | |
if (!s.length) { | |
return ++count; | |
} | |
if (s.length === 1) { | |
if (availableNumStr[s]) { | |
return ++count; | |
} | |
return 0 | |
} | |
if (s.length >= 2) { | |
const fristChar = s.slice(0, 1); | |
const fristTwoChars = s.slice(0, 2); | |
let waysOfExcludeFirstChar = !availableNumStr[fristChar] ? 0 : decodeWays(s.slice(1), count); | |
let waysOfExcludeFirstTwoChars = !availableNumStr[fristTwoChars] ? 0 : decodeWays(s.slice(2), count); | |
const result = waysOfExcludeFirstChar + waysOfExcludeFirstTwoChars; | |
// 在返回接过前先将结果缓存起来: | |
cache[s] = result; | |
return result; | |
} | |
} | |
return decodeWays(s, 0) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment