当前位置: 首页 > news >正文

Edit Distance

题目描述

The edit distance between two strings is the minimum number of operations required to transform one string into the other.
The allowed operations are:

Add one character to the string.
Remove one character from the string.
Replace one character in the string.

For example, the edit distance between LOVE and MOVIE is 2, because you can first replace L with M, and then add I.
Your task is to calculate the edit distance between two strings.

输入

The first input line has a string that contains n characters between A–Z.
The second input line has a string that contains m characters between A–Z.
Constraints
1 ≤ n,m ≤ 5000

输出

Print one integer: the edit distance between the strings.

样例输入
LOVE
MOVIE
样例输出
2
思路分析

本题样例求解:

j=0j=1j=2j=3j=4j=5
MOVIE
i=0012345
i=1L112345
i=2O221234
i=3V332123
i=4E443222

递归

MOVIE与LOVE最后的字符均为‘E’,可以无痛转化成MOVI与LOV之间的编辑距离。

MOVI与LOV最后的字符不相等,可以考虑对MOVI进行操作,或将其最后一位删除,或将其最后一位改为‘V’,或在其后面加‘V’。

……

如果一个字符串为空而另一个字符串非空,那么编辑距离就为非空字符串的长度。

递归会大量重复计算导致超时。

动态规划

dp[i][j]存储 第一个字符串的前i个字符 与 第二个字符串的前j个字符 的 最短操作距离。

注意初始化,提前处理任一字符串为空的情况。

当a[i]==b[j],dp[i+1][j+1]=dp[i][j]。

当a[i]!=b[j],此时需要对字符串进行增删改三种操作,该操作编辑距离为1,此时dp[i+1][j+1]=min(dp[i][j],dp[i+1][j],dp[i][j+1])+1。

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string a,b;
int m,n;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>a>>b;m=a.size();n=b.size();vector<vector<int>>dp(m+1,vector<int>(n+1,0));for(int i=0;i<=n;i++){dp[0][i]=i;}for(int j=0;j<=m;j++){dp[j][0]=j;}for(int i=1;i<=m;i++){for(int j=1;j<=n;j++){if(a[i-1]==b[j-1]){dp[i][j]=dp[i-1][j-1];}else{int c[3]={dp[i][j-1],dp[i-1][j],dp[i-1][j-1]};sort(c,c+3);dp[i][j]=c[0]+1;}}}cout<<dp[m][n];return 0;
}
http://www.dtcms.com/a/326810.html

相关文章:

  • 传统制造业减人不减效:一线用工优化的3个投入方向,用对工具比盲目裁员更关键
  • 对抗样本攻击检测与防御
  • 车载软件架构 --- 车辆量产后怎么刷写Flash Bootloader
  • BLE ADV
  • special topic 9 (2) and 1011(1)division one
  • 深入解析Windows系统下UDP绑定失败的原理与系统级解决方案
  • 数据库三范式入门教程
  • Windows11 PowerShell CMD
  • Ascend DrivingSDK 中的 modulated_deform_conv2d(一)
  • GESP2023年9月认证C++一级( 第三部分编程题(1)买文具)
  • MATLAB实现遗传算法求解路网路由问题
  • PTE之路--03文
  • 【08-神经网络介绍】
  • 北京-4年功能测试2年空窗-报培训班学测开-第七十三天-投递简历-[特殊字符][特殊字符]
  • Linux驱动学习day27天(USB驱动理论部分)
  • SSR-code 项目复刻与3D模型生成实现
  • nomachine的安装和使用
  • 华清远见25072班C语言学习day6
  • 操作系统1.5:操作系统引导
  • 101. 孤岛的总面积
  • 下一代防火墙组网
  • 晓知识: 动态代理与静态代理的区别
  • Android模块化架构深度解析:从设计到实践
  • 强联通分量(重制版)
  • 环境配置-拉取NVIDIA Docker镜像时出现401Unauthorized错误
  • 数据填报是什么?数据填报工具有哪些?
  • 黑马程序员mysql基础篇笔记
  • 自定义switch with icon
  • 使用Pytest进行接口自动化测试(三)
  • 深入了解torch框架