Skip to content

Commit

Permalink
feat(leecode): 72.编辑距离
Browse files Browse the repository at this point in the history
  • Loading branch information
z979054461 committed Mar 30, 2024
1 parent 2792854 commit 91bc786
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 0 deletions.
75 changes: 75 additions & 0 deletions docs/10.LeeCode/72.编辑距离.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
title: 72.编辑距离
date: 2024-03-30
lang: 'zh-CN'
sidebar: 'auto'
categories:
- LeeCode
tags:
location: HangZhou
---

# Heading

[[toc]]

[72.编辑距离](https://leetcode.cn/problems/edit-distance/description/)

Tags: algorithms string dynamic-programming

Langs: c cpp csharp dart elixir erlang golang java javascript kotlin php python python3 racket ruby rust scala swift typescript

- algorithms
- Medium (62.84%)
- Likes: 3347
- Dislikes: -
- Total Accepted: 463K
- Total Submissions: 737.2K
- Testcase Example: '"horse"\n"ros"'

<p>给你两个单词&nbsp;<code>word1</code> 和&nbsp;<code>word2</code>, <em>请返回将&nbsp;<code>word1</code>&nbsp;转换成&nbsp;<code>word2</code> 所使用的最少操作数</em> &nbsp;。</p>

<p>你可以对一个单词进行如下三种操作:</p>

<ul>
<li>插入一个字符</li>
<li>删除一个字符</li>
<li>替换一个字符</li>
</ul>

<p>&nbsp;</p>

<p><strong>示例&nbsp;1:</strong></p>

<pre>
<strong>输入:</strong>word1 = "horse", word2 = "ros"
<strong>输出:</strong>3
<strong>解释:</strong>
horse -&gt; rorse (将 'h' 替换为 'r')
rorse -&gt; rose (删除 'r')
rose -&gt; ros (删除 'e')
</pre>

<p><strong>示例&nbsp;2:</strong></p>

<pre>
<strong>输入:</strong>word1 = "intention", word2 = "execution"
<strong>输出:</strong>5
<strong>解释:</strong>
intention -&gt; inention (删除 't')
inention -&gt; enention (将 'i' 替换为 'e')
enention -&gt; exention (将 'n' 替换为 'x')
exention -&gt; exection (将 'n' 替换为 'c')
exection -&gt; execution (插入 'u')
</pre>

<p>&nbsp;</p>

<p><strong>提示:</strong></p>

<ul>
<li><code>0 &lt;= word1.length, word2.length &lt;= 500</code></li>
<li><code>word1</code> 和 <code>word2</code> 由小写英文字母组成</li>
</ul>

<<< @/src/LeeCode/72.编辑距离.js
42 changes: 42 additions & 0 deletions src/LeeCode/72.编辑距离.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* @lc app=leetcode.cn id=72 lang=javascript
*
* [72] 编辑距离
* 动态规划 Hard
*/

// @lc code=start
/**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function (word1, word2) {
const dp = []
const m = word1.length
const n = word2.length

if (m * n === 0) {
return m + n
}

for (let i = 0; i < m + 1; i++) {
dp[i] = [i]
}
for (let j = 0; j < n + 1; j++) {
dp[0][j] = j
}

for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (word1[i] === word2[j]) {
dp[i + 1][j + 1] = dp[i][j]
} else {
dp[i + 1][j + 1] = 1 + Math.min(dp[i][j], dp[i][j + 1], dp[i + 1][j])
}
}
}

return dp[m][n]
}
// @lc code=end

0 comments on commit 91bc786

Please sign in to comment.