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

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.xdnf.cn/news/17660.html

相关文章:

  • react中父子数据流动和事件互相调用(和vue做比较)
  • GO学习记录三
  • 基于MongoDB/HBase的知识共享平台的设计与实现
  • 【Dv3Admin】菜单转换选项卡平铺到页面
  • Excel 连接阿里云 RDS MySQL
  • 5G 非地面网络(NTN)最专业的方案
  • 高并发场景下分布式ID生成方案对比与实践指南
  • 在 .NET Core 5.0 中启用 Gzip 压缩
  • 从ELF到进程间通信:剖析Linux程序的加载与交互机制
  • 玩转Docker | 使用Docker部署Trilium Notes知识库工具
  • 5G NTN 卫星测试产品
  • word格式设置-论文写作,样式,字号等
  • WPF之绑定!
  • LeetCode——241.为运算表达式设计优先级
  • 在 RHEL9 上搭建企业级 Web 服务(Tomcat)
  • Android Audio实战——获取活跃音频类型(十五)
  • 深度学习与遥感入门(五)|GAT 构图消融 + 分块全图预测:更稳更快的高光谱图分类(PyTorch Geometric 实战)
  • 【数据可视化-86】中国育儿成本深度可视化分析(基于《中国统计年鉴2023》数据):用Python和pyecharts打造炫酷可视化大屏
  • 论文阅读 arxiv 2024 MemGPT: Towards LLMs as Operating Systems
  • Apache IoTDB 全场景部署:基于 Apache IoTDB 的跨「端-边-云」的时序数据库 DB+AI
  • Java 之抽象类和接口
  • SSH远程连接TRAE时显示权限被拒绝检查方案
  • 可视化程序设计(4) - 第一个图形窗口程序
  • Java进阶之单列集合Set接口下的通用方法
  • Linux下的软件编程——标准IO
  • ECharts Y轴5等分终极解决方案 - 动态适配缩放场景
  • 后量子密码学的迁移与安全保障:迎接量子时代的挑战
  • NLP---IF-IDF案例分析
  • FreeRTOS学习:优化系统
  • LeetCode_哈希表