javascript - 第一个stackoverflow问题 每日编码问题#7
问题描述
我正在处理我的每日编码问题#7,并且很难找到一种方法来测试这个算法,看看它是否会起作用。这是问题:
早上好!这是您今天的编码面试问题。
Facebook 提出了这个问题。
给定映射 a = 1, b = 2, ... z = 26 和编码消息,计算可以解码的方式数。
例如,消息“111”将给出 3,因为它可以被解码为“aaa”、“ka”和“ak”。
您可以假设消息是可解码的。例如,不允许使用“001”。
这是我找到的解决方案。知道如何确认这将解码吗?
function numDecodingsRHelper(message, index) {
if (index === message.length) return 1;
if (message.charAt(index) === '0') return 0;
// Single Number
let totalDecodings = numDecodingsRHelper(message, index + 1);
if (index < message.length - 1) {
// Double Number
const doubleNum = parseInt(message.substring(index, index + 2), 10);
if (doubleNum >= 10 && doubleNum <= 26)
totalDecodings += numDecodingsRHelper(message, index + 2);
}
return totalDecodings;
}
解决方案
这是更好的解决方案。我发现其他几个解决方案的问题是它们只从字符串输入中返回可能的字母序列列表,而不是将总数作为整数返回。如在问题“111”中使用的示例返回 3,但我发现的大多数解决方案都会返回一个类似“aaa”、“ka”和“ak”的列表。
function decode_cnt_no_zero(message) {
let length = message.length
if (length <=1) { return 1 }
if (length >=2) { var parsed = parseInt(message.substring(0,2),10) if (parsed >=0 && parsed <= 26) { return (decode_cnt_no_zero(message.substring(1,length)) + decode_cnt_no_zero(message.substring(2, length))) } return decode_cnt_no_zero(message.substring(1, length)) } }
推荐阅读
- layer - 如何在mapboxgl内的图层中使用Mapbox的tileset Id?
- java - 如何使用 Google Drive API v3 获取组织的 Google Workspace 中所有用户的所有文件?
- css - 所有 HTML 树的第一个元素的 CSS 属性
- java - timeDifference(DateTime) 对于 OpenNTF Domino API 中的 DateTime 类型不明确
- reactjs - 如何使用打字稿编写 es6 onchange 方法并做出反应?
- rust - 处理拒绝时获取当前路径
- javascript - 如何在 JavaScript 的控制台中输入水平线?
- python - 如何使用 kivy v2.0.0 播放视频?
- swiftui - 如何为 SwiftUI ViewRepresentable 制作自定义 MKMapView 委托操作?
- python - Python - 将函数应用于二维数组