题目链接: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}
算法 :
public int minDistance(String word1, String word2) { char sc[] = word1.toCharArray(); char tc[] = word2.toCharArray(); int [][] c = new int [word1.length() + 1 ][word2.length() + 1 ]; for ( int i = 0 ; i <= word1.length(); i++) { c[i][0 ] = i; } for ( int j = 0 ; j <= word2.length(); j++) { c[0 ][j] = j; } for ( int i = 1 ; i <= word1.length(); i++) { for ( int j = 1 ; j <= word2.length(); j++) { int n1 = c[i - 1 ][j] + 1 ; int n2 = c[i][j - 1 ] + 1 ; int n3 = c[i - 1 ][j - 1 ]; if (sc[i - 1 ] != tc[j - 1 ]) n3++; c[i][j] = Math.min(n1, n2); c[i][j] = Math.min(c[i][j], n3); } } return c[word1.length()][word2.length()]; }