博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Edit Distance(字符串编辑距离DP)
阅读量:7098 次
发布时间:2019-06-28

本文共 1417 字,大约阅读时间需要 4 分钟。

 

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

 思路:题意求字符串的最小编辑距离。设状态为f[i][j],表示A[0][i] B[0][j]之间的最小编辑距离。

forexamplr:str1c str2d

1、c==d f[i][j]=f[i-1][j-1] 2、c!=d   (1)如果将c换成d 则f[i][j]=f[i-1][j-1]+1 (2)如果在c后面添加一个d f[i][j]=f[i][j-1]+1 (3)如果将c删除 f[i][j]=f[i-1][j-1]+1
   简单的状态方程为
dp[i, j] = min { dp[i - 1, j] + 1,  dp[i, j - 1] + 1, dp[i - 1, j - 1] + (s[i] == t[j] ? 0 : 1) }
1 class Solution { 2 public: 3     int minDistance(string word1, string word2) { 4          5         const int n=word1.size(); 6         const int m=word2.size(); 7          8         vector
> f(n+1,vector
(m+1,0)); 9 10 for(int i=0;i<=n;i++)11 f[i][0]=i;12 13 for(int j=0;j<=m;j++)14 f[0][j]=j;15 16 for(int i=1;i<=n;i++)17 for(int j=1;j<=m;j++)18 if(word1[i-1]==word2[j-1])19 f[i][j]=f[i-1][j-1];20 else{21 f[i][j]=min(f[i-1][j-1],min(f[i-1][j],f[i][j-1]))+1;22 23 }24 25 return f[n][m];26 }27 };

 

转载于:https://www.cnblogs.com/xiaoying1245970347/p/4721621.html

你可能感兴趣的文章
python 的StringIO
查看>>
第三个阶段事后诸葛亮
查看>>
java中的sql语句中如果有like怎么写
查看>>
【原创】驱动加载之StartService
查看>>
1751: [Usaco2005 qua]Lake Counting
查看>>
【BZOJ】4753: [Jsoi2016]最佳团体 01分数规划+树上背包
查看>>
iOS 获取设备信息之UIDevice的使用,Swift 基于 API
查看>>
IntelliJ cannot log in to GitHub上传github报错解决
查看>>
MySQL强制性操作
查看>>
timestamp与timedelta,管理信息系统概念与基础
查看>>
重写对象ToString方法
查看>>
备忘: C++中的 vector 容器
查看>>
smt中查看图片与视频缩略图中,如何获得小视频的长度。
查看>>
图片(img标签)的onerror事件
查看>>
2013应届毕业生“百度”校招应聘总结
查看>>
CentOS系统启动流程
查看>>
myEclipse的Aptana studio插件安装时出现Error opening the editor.
查看>>
Mysql 知识(1)
查看>>
根据不同选择显示不同单价的逻辑
查看>>
“整个场面我Hold住!”软件测试计划
查看>>