问题描述:
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]时,比较麻烦了,分三种情况:
- word1插入一个字符,那么此时就变成了dist[i,j] = dist[i-1,j]+1
- Word1删除一个字符(等价于Word2插入一个字符),那么此时就变成了dist[i,j] = dist[i,j-1]+1。
- 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];
}
本文详细解析了如何使用动态规划算法解决两个字符串之间的编辑距离问题,包括插入、删除和替换操作,并给出了具体的状态转移方程及实现代码。
269

被折叠的 条评论
为什么被折叠?



