[leetcode-72]Edit Distance(C)

来源:互联网 发布:电脑日程提醒软件 编辑:程序博客网 时间:2024/05/25 01:35

问题描述:
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

分析:这道题,我猜想到使用动态规划算法,可是却不知道怎么写状态转移方程。在看了很多网友的博客之后,才逐渐明白。DP算法要求从0开始,逐渐推到最后一个式子。令i,j分别为word1和word2前i个字符与前j个字符的距离。
那么当word1[i]==word2[j]时,那么很自然的,dist[i,j] = dist[i-1,j-1].
那么当word1[i] != word2[j]时,比较麻烦了,分三种情况:

  1. word1插入一个字符,那么此时就变成了dist[i,j] = dist[i-1,j]+1
  2. Word1删除一个字符(等价于Word2插入一个字符),那么此时就变成了dist[i,j] = dist[i,j-1]+1。
  3. word1替换一个字符,那么就变成了dist[i,j] = dist[i-1,j-1]+1;
    然后我们取这三者的最小值,即
    dist[i,j]=min(dist[i-1,j]+1,dist[i,j-1]+1,dist[i-1,j-1]+f(i,j)||f(i,j)=0(word1[i-1]=word2[j-1]) f(i,j)=1(word1[i-1]=word2[j-1])

代码如下:12ms

int minDistance(char* word1, char* word2) {    int rowWidth = strlen(word1);    int colWidth = strlen(word2);    int *matrix = (int *)malloc(sizeof(int)*(rowWidth+1)*(colWidth+1));    const int matrixWidth = colWidth+1;    //init array    for(int col = 0;col<=colWidth;col++)        matrix[col] = col;    for(int row = 0;row<=rowWidth;row++)        matrix[row*matrixWidth] = row;    for(int row = 1;row<=rowWidth;row++){        for(int col = 1;col<=colWidth;col++){            int weight = 0;            if(word1[row-1]!=word2[col-1])                weight = 1;//替换            int val1 = matrix[(row-1)*matrixWidth+col-1]+weight;//matrix[row-1,col-1]            int val2 = matrix[(row-1)*matrixWidth+col]+1;//matrix[row-1,col]            int val3 = matrix[row*matrixWidth+col-1]+1;//matrix[row,col-1]            int min = val1<val2?val1:val2;            matrix[row*matrixWidth+col] = min<val3?min:val3;        }    }    return matrix[rowWidth*matrixWidth+colWidth];}
0 0