题目链接:https://leetcode.com/problems/edit-distance/ 题目:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
思路:
c[i][j]表示word1的0~i子串和word2的0~j子串的最小编辑距离。状态转移方程:
如果sc[i]==tc[j]即最后一个字符相等 : c[i][j]=min{c[i-1][j],c[i][j-1],c[i-1][j-1]}
否则最后一个字符需要替换增加1个编辑距离:c[i][j]=min{c[i-1][j],c[i][j-1],c[i-1][j-1]+1}
算法:
1. public int minDistance(String word1, String word2) {
2. char sc[] = word1.toCharArray();
3. char tc[] = word2.toCharArray();
4. int[][] c = new int[word1.length() + 1][word2.length() + 1];
5.
6. for (int i = 0; i <= word1.length(); i++) {
7. 0] = i;
8. }
9. for (int j = 0; j <= word2.length(); j++) {
10. 0][j] = j;
11. }
12.
13. for (int i = 1; i <= word1.length(); i++) {
14. for (int j = 1; j <= word2.length(); j++) {
15. int n1 = c[i - 1][j] + 1;
16. int n2 = c[i][j - 1] + 1;
17. int n3 = c[i - 1][j - 1];
18. if (sc[i - 1] != tc[j - 1])
19. n3++;
20. c[i][j] = Math.min(n1, n2);
21. c[i][j] = Math.min(c[i][j], n3);
22. }
23. }
24. return c[word1.length()][word2.length()];
25. }