LeetCode-Edit Distance

2015-07-20 17:44:39 · 作者: · 浏览: 3

?

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

分析:

设状态为f[i][j],表示A[0,i] 和B[0,j] 之间的最小编辑距离。设A[0,i] 的形式是str1c,B[0,j] 的形式是str2d,
1. 如果c==d,则f[i][j]=f[i-1][j-1];
2. 如果c!=d,
(a) 如果将c 替换成d,则f[i][j]=f[i-1][j-1]+1;
(b) 如果在c 后面添加一个d,则f[i][j]=f[i][j-1]+1;
(c) 如果将c 删除,则f[i][j]=f[i-1][j]+1;

源码Java版本
算法分析:二维动态规划。时间复杂度O(m*n),空间复杂度O(m*n)

?

public class Solution {
    public int minDistance(String word1, String word2) {
        int m=word1.length();
        int n=word2.length();
        int[][] f=new int[m+1][n+1];
        for(int i=0;i
  
   

?