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


class Solution {
public:

/*
超时
int minDistance(string word1, string word2) {

int len1,len2;
len1=word1.size();
len2=word2.size();
return solve(word1,0,len1,word2,0,len2);
}

int solve(string word1,int index1,int len1,string word2,int index2,int len2)
{
if(index1>=len1)
{
if(index2>=len2)
return 0;
else
return len2-index2;
}

if(index2>=len2)
{
if(index1>=len1)
return 0;
else
return len1-index1;
}

if(word1[index1]==word2[index2])
return solve(word1,index1+1,len1,word2,index2+1,len2);
else
{
int t1=solve(word1,index1+1,len1,word2,index2,len2);
int t2=solve(word1,index1,len1,word2,index2+1,len2);
int t3=solve(word1,index1+1,len1,word2,index2+1,len2);
return min(min(t1,t2),t3)+1;
}
}*/

int minDistance(string word1, string word2) {

int len1=word1.size()+1,len2=word2.size()+1;
vector< vector<int>> dp(len1,vector<int>(len2));

for(int i=0;i<len1;i++)//与空串的距离
dp[i][0]=i;
for(int i=0;i<len2;i++)
dp[0][i]=i;

for(int i=1;i<len1;i++)
for(int j=1;j<len2;j++)
{
if(word1[i-1]==word2[j-1])
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=min(dp[i][j-1],min(dp[i-1][j],dp[i-1][j-1]))+1;
}
return dp[len1-1][len2-1];
}
};