https://leetcode.com/problems/edit-distance/description/?envType=study-plan-v2&envId=leetcode-75
최소 편집 거리(Minimum Edit Distance) 알고리즘: 두 개의 문자열이 같아지기 위해 몇 번의 삽입(insert), 삭제(delete), 교체(replace) 가 이뤄져야 하는지 그 최소 갯수를 구하는 알고리즘
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m+1][n+1];
for (int i = 1; i <= m; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= n; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1.charAt(i-1) == word2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1];
continue;
}
int insert = dp[i][j-1];
int delete = dp[i-1][j];
int replace = dp[i-1][j-1];
dp[i][j] = Math.min(insert, Math.min(delete, replace)) + 1;
}
}
return dp[m][n];
}
1-based indexing. 배열 선언과 최종 return 문을 한번 생각해볼 것.
(word의 indexing 은 1부터 시작. 단어의 첫번째 글자를 1로 생각해서 배열 dp 상에서 표현해줌. 리턴문도 length 의 위치를 확인하면 된다)
(참고: https://leetcode.com/problems/edit-distance/solutions/3230662/clean-codes-full-explanation-dynamic-programming-c-java-python3/?envType=study-plan-v2&envId=leetcode-75)
dp[i][j] : word1[0..i-1] 이 word2[0..j-1] 이 될 수 있는 최소 편집 거리
이미 같기 때문에 뭘 삽입/삭제/교체 해 줄 필요가 없다.
dp[i][j] = dp[i-1][j-1]
예를 들어 sprout 을 sport 로 변환시키려고 한다면 다음 세 가지 경우를 살펴볼 수 있다.
spr ➡️ spo (dp[3][3]) i==3, j==3
(1) 삽입: spr ➡️ sp (dp[i][j-1]) 를 알고 있다면,
해당 연산 + word1 쪽 index i 위치에 word2의 index j-1(o)를 삽입해주는 연산 1번
(2) 삭제: sp ➡️ spo (dp[i-1][j]) 를 알고 있다면,
해당 연산 + word1에서 index i-1(r)을 삭제하는 연산 1번
(3) 교체: sp ➡️ sp (dp[i-1][j-1]) 를 알고 있다면,
해당 연산에 맨 마지막 문자를 교체해주는 연산 1번
base case:
word2 index j가 0일 경우 word1을 i만큼 삭제 해주면 되고,
word1 index i 가 0일 경우 word2 길이 j만큼 삽입해주면 된다.
여기서, 우리는 word1에서 word2로 가는 모든 연산을 고려합니다. 즉, 삽입 연산이라고 할 때, 우리는 word1 뒤에 word2의 j번째 문자와 일치하는 새 문자를 삽입합니다. 따라서 이제 word1의 i개 문자를 word2의 j - 1개 문자와 일치시켜야 합니다. 다른 두 연산도 마찬가지입니다.