首页 > 解决方案 > 第一个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;
} 

标签: javascript

解决方案


这是更好的解决方案。我发现其他几个解决方案的问题是它们只从字符串输入中返回可能的字母序列列表,而不是将总数作为整数返回。如在问题“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)) } }

推荐阅读