LeetCode Edit Distance

来源:互联网 发布:python游戏开发教程 编辑:程序博客网 时间:2024/06/06 02:52

题目

Given two words word1 and word2, find the minimum number of steps required to convertword1 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,匹配word1[1~i]与word2[1~j]的代价cost[i,j]为:

1、如果word1[i]==word2[j],则cost[i,j]=cost[i-1,j-1];

2、如果不等,则cost[i,j]=min(cost[i-1,j-1],cost[i-1,j],cost[i,j-1])+1

 

代码:

class Solution {public:    int minDistance(string word1, string word2) {        int size1=word1.size(),size2=word2.size();vector<vector<int>> cost(size1+1,vector<int>(size2+1,0));//cost[i][j]记录word1(1~i)与word2(1~j)的匹配代价int i,j;for(i=0;i<=size1;i++)cost[i][0]=i;for(j=0;j<=size2;j++)cost[0][j]=j;for(i=1;i<=size1;i++)//dp{for(j=1;j<=size2;j++){if(word1[i-1]==word2[j-1])//相应位置字符相同cost[i][j]=cost[i-1][j-1];else//不同时考虑三种操作中总代价最小的cost[i][j]=min(min(cost[i-1][j],cost[i][j-1]),cost[i-1][j-1])+1;}}return cost[size1][size2];    }};


 

 

 

 


 

 

0 0