编辑问题+动态规划 编辑red字符串

66 阅读2分钟

题目

fc85e92818f7c04340733e1a63f0ca22.png

  • 递归从左往右模型,从第三个位置开始,进行可能性分析,分别分析该位置取r、e、d三种的情况,然后往右递归,将前面两个位置的选择传递给后面
class Info {
  constructor(good, cost) {
    this.mostGoodE = good; // 收益
    this.minCost = cost; // 代价
  }
}
// prepre: i-2 位置字符
// pre: i-1 位置字符
function process(str, i, prepre, pre) {
  // 越界无法构造
  if (i === str.length) {
    return new Info(0, 0);
  }

  // 可能性1
  // i 位置字符变成 r 的收益
  let cur1Value = prepre === "d" && pre === "e" ? 1 : 0;
  // i 位置字符变成 r 的代价
  let cur1Cost = str[i] === "r" ? 0 : 1;
  // i 位置后序结果: 当前的 pre 是下一个位置的 prepre ,当前 i 位置变化字符是下一个位置的 pre
  let info1 = process(str, i + 1, pre, "r");
  // 可能性 1 的总体收益
  let p1Value = cur1Value + info1.mostGoodE;
  // 可能性 1 的总体代价
  let p1Cost = cur1Cost + info1.minCost;

  // 可能性2
  // i 位置字符变成 e 的收益
  let cur2Value = 0; // i-1、i-2位置无法构成题意
  // i 位置字符变成 e 的代价
  let cur2Cost = str[i] === "e" ? 0 : 1;
  // i 位置后序结果: 当前的 pre 是下一个位置的 prepre ,当前 i 位置变化字符是下一个位置的 pre
  let info2 = process(str, i + 1, pre, "e");
  // 可能性 2 的总体收益
  let p2Value = cur2Value + info2.mostGoodE;
  // 可能性 2 的总体代价
  let p2Cost = cur2Cost + info2.minCost;

  // 可能性3
  // i 位置字符变成 d 的收益
  let cur3Value = prepre === "r" && pre === "e" ? 1 : 0;
  // i 位置字符变成 d 的代价
  let cur3Cost = str[i] === "d" ? 0 : 1;
  // i 位置后序结果: 当前的 pre 是下一个位置的 prepre ,当前 i 位置变化字符是下一个位置的 pre
  let info3 = process(str, i + 1, pre, "d");
  // 可能性 3 的总体收益
  let p3Value = cur3Value + info3.mostGoodE;
  // 可能性 3 的总体代价
  let p3Cost = cur3Cost + info3.minCost;

  let mostE = 0,
    minCost = Infinity;

  if (mostE < p1Value) {
    mostE = p1Value;
    minCost = p1Cost;
  } else if (mostE === p1Value) {
    minCost = Math.min(minCost, p1Cost);
  }

  if (mostE < p2Value) {
    mostE = p2Value;
    minCost = p2Cost;
  } else if (mostE === p2Value) {
    minCost = Math.min(minCost, p2Cost);
  }

  if (mostE < p3Value) {
    mostE = p3Value;
    minCost = p3Cost;
  } else if (mostE === p3Value) {
    minCost = Math.min(minCost, p3Cost);
  }

  return new Info(mostE, minCost);
}