Edit Distance (leetcode)

题目:

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;  
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值