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

      嗯~~这道题用dp来做~~

#include<iostream>
#include<string>
#include<cstring>	
int dp[1000][1000];
int minn(int a,int b,int c)
{
	if(a<=b&&a<=c)
	{
		return a;
	}
	else if(b<=a&&b<=c)
	{
		return b;
	}
	else if(c<=a&&c<=b)
	{
		return c;
	}
}
int main() 
{
	std::ios::sync_with_stdio(false);
	std::string yuan;
	std::string md;
	std::cin>>yuan>>md;
	int leny=yuan.length();
	int lenm=md.length();
	for(int s=0;s<=leny;s++)
	{
		dp[s][0]=s;
	}
	for(int s=0;s<=lenm;s++)
	{
		dp[0][s]=s;
	}
	for(int s=1;s<=leny;s++)
	{
		for(int x=1;x<=lenm;x++)
		{
			int spot=1;
			if(yuan[s-1]==md[x-1])
			{
				spot=0;
			}
			dp[s][x]=minn(dp[s-1][x]+1,dp[s][x-1]+1,dp[s-1][x-1]+spot);
		}
	}
	for(int s=0;s<=leny;s++)
	{
		for(int x=0;x<=lenm;x++)
		{
			std::cout<<dp[s][x];
		}
		std::cout<<std::endl;
	}
	std::cout<<dp[leny][lenm]<<std::endl;
	return 0;
}

全部评论

相关推荐

Hello_WordN:咱就是说,除了生命其他都是小事,希望面试官平安,希望各位平时也多注意安全
点赞 评论 收藏
分享
11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务