edit distance

本文介绍了一个使用动态规划解决字符串转换问题的算法实现。通过插入、删除或替换字符操作,找到将一个字符串转换为另一个字符串所需的最小步骤数。文章提供了一段C++代码,详细展示了如何初始化DP数组并迭代填充它来解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值