题目:
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
题目来源:https://oj.leetcode.com/problems/edit-distance/
解题思路:动态规划,两个字符串相同,则可以修改,插入或删除,通过比较三种改变的次数,动态求解最优次数
参考:《leetcode题解》
#include<iostream>
#include <vector>
#include<string>
using namespace std;
int minDistance(string word1, string word2)
{
if(word1.empty())
return word2.size();
if(word2.empty())
return word1.size();
const int M=word1.size();
const int N=word2.size();
//f[i][j]表示word1中的i个字符和word2中的j个字符匹配需要改变的字符数
vector<vector<int> > f(M+1,vector<int>(N+1,0));
for(int i=0;i<=M;i++)
f[i][0]=i;
for(int i=0;i<=N;i++)
f[0][i]=i;
for(int i=1;i<=M;i++)
{
for(int j=1;j<=N;j++)
{
if(word1[i-1]==word2[j-1])
f[i][j]=f[i-1][j-1];
else
f[i][j]=1+min(min(f[i-1][j],f[i][j-1]),f[i-1][j-1]);
}
}
return f[M][N];
}
int main()
{
string word1="sea",word2="ate";
int result=minDistance(word1,word2);
system("pause");
return 0;
}