js实现最短编辑距离算法

175 阅读1分钟
<html>
  <body>
    <div>str1: <input id="str1" /></div>
    <div>str2: <input id="str2" /></div>

    <button onclick="getDP()">计算</button>

    <div>distance: <span id="result"></span></div>
  </body>
  <script>
    const getDP = () => {
      const str1 = document.getElementById("str1")?.value || "";
      const str2 = document.getElementById("str2")?.value || "";

      const dp = (i, j) => {
        if (i === -1) return j + 1;
        if (j === -1) return i + 1;
        if (str1[i] === str2[j]) {
          return dp(i - 1, j - 1);
        } else {
          const a = dp(i, j - 1) + 1; // 增加
          const d = dp(i - 1, j) + 1; // 删除
          const t = dp(i - 1, j - 1) + 1; // 替换
          return Math.min(a, d, t);
        }
      };

      const distance = dp(str1.length - 1, str2.length - 1);
      document.getElementById("result").innerText = distance;
    };
  </script>
</html>