# 72. Edit Distance (Hard)

https://leetcode.com/problems/edit-distance/

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

1. Insert a character
2. Delete a character
3. Replace a character

Example 1:

```Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
```

Example 2:

```Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
```

## Solutions

``````class Solution {

public int minDistance(String word1, String word2) {
if (word1 == null && word2 == null) {
return 0;
}

if (word1 == null) {
return word2.length();
}

if (word2 == null) {
return word1.length();
}

int len1 = word1.length();
int len2 = word2.length();

int[][] dp = new int[len1 + 1][len2 + 1];

// length of word1 is i, word2 is 0, update the edit distance
for (int i = 0; i <= len1; i++) {
dp[i] = i;
}

// length of word2 is i, word1 is 0, update the edit distance
for (int j = 0; j <= len2; j++) {
dp[j] = j;
}

for (int i = 1; i <= len1; i++) {

// Assume word1's length is i, work out the edit distance when j is 1,2,3,...len2 respectively.
for (int j = 1; j <= len2; j++) {

// Following operations can be considered as calculating edit distance from word1[0:i-1] to
// word2[0:j-1]

// what if we delete the last char of word1[0:i-1], then we adopt the edit distance from
// word1[0:i-2] to word2[j-1]
int del = dp[i - 1][j] + 1;

// what if we delete the last char of word2[0:j-1], then we adopt the edit distance from
// word1[0:i-1] to word2[j-2]
int ins = dp[i][j - 1] + 1;

// what if we replace word1[i-1] with word2[j-1] if not the same, then we adopt the edit distance
// from word1[0:i-2] to word2[j-2]
int rep = dp[i - 1][j - 1];

// No need to change if the last char is the same, following i-1 and j-1 is the index, the
// actual meaning is the ith char in word1 and jth char in word2.
if (word1.charAt(i - 1) != word2.charAt(j - 1)) {
rep += 1;
}

dp[i][j] = min(del, ins, rep);
}
}

return dp[len1][len2];
}

private int min(int x, int y, int z) {
int min = Math.min(x, y);

return Math.min(min, z);
}
}
``````