递归 字符串转换字母

54 阅读1分钟

题目 规定1和A对应,2和B对应,...,26和Z对应,如果字符串为'111'那么可以转换成'AAA'、'KA'或'AK',给定一个字符串,求一共有多少种转化结果

  • 如果当前index字符为1,那么可以有两种结构,index或者(index和index+1)位置上字符两种结构
  • 如果当前index字符为2,那么可能有两种结构,如果index+1位置上的字符<'6'那么会有index或者(index和index+1)位置上的字符组成的两种结果,如果index+1位置上的字符>'6'那么只有index位置上的字符一种结构
  • 如果当前index字符为0,0没有字母对应,那么无论怎样结果都为0
  • 如果当前index字符大于3,那么与下一个位置字符结合一定大于26,因此只有index位置上的字符一种结构

image.png

function count(str, index) {
  // 当遍历所有字符后,说明当前情况转换结束,返回1种结果
  if (index === str.length) {
    return 1;
  }

  if (str[index] === "0") {
    return 0;
  }
  if (str[index] === "1") {
    let res = count(str, index + 1);
    if (index + 1 < str.length) {
      res += count(str, index + 2);
    }
    return res;
  }

  if (str[index] === "2") {
    let res = count(str, index + 1);
    if (index + 1 < str.length && str[index] >= "0" && str[index] <= "6") {
      res += count(str, index + 2);
    }
    return res;
  }

  if (str[index] >= "3" || str[index] <= "9") {
    return count(str, index + 1);
  }
}

console.log(count("123", 0));