第十五周LeetCode
来源:互联网 发布:最后一炮优化很烂 编辑:程序博客网 时间:2024/06/05 11:59
题目
Edit Distance
难度 hard
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
实现思路
这个题是书上的例题。假设E[i][j]表示把word1的前i个字符与word2的前j个字符对齐所需的最小操作,最右端有三种对齐方式:
* P P
O * O*表示占位符,第一种情况表示dp[i][j]为dp[i-1][j]+1,第二种情况表示dp[i][j]为dp[i][j-1]+1,第三种情况,如果O和P相等,那么不需要操作,否则需要进行替换操作。因此dp[i][j]=min(dp[i][j-1]+1,dp[i-1][j]+1,dp[i-1][j-1]+(int)(word1[i-1]!=word2[j-1]))。
实现代码
int minDistance(string word1, string word2) { vector<vector<int>> E(word1.length()+1,vector<int>(word2.length()+1,0)); for (int i = 0; i <= word1.length(); i++) { E[i][0] = i; } for (int j = 0; j <= word2.length(); j++) { E[0][j] = j; } for (int i = 1; i <= word1.length(); i++) { for (int j = 1; j <= word2.length(); j++) { int x = E[i-1][j]+1; int y = E[i][j-1]+1; int z = E[i-1][j-1]+(int)(word1[i-1]!=word2[j-1]); E[i][j]=min(min(x,y),z); } } return E[word1.length()][word2.length()]; }
阅读全文
0 0
- 第十五周leetcode题
- leetcode-第十五周
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- 第十五周LeetCode
- LeetCode题解 第十五周
- Leetcode 算法习题 第十五周
- 第十五周LeetCode算法题两道
- leetcode【第十五周】路径求和 【二】
- 第十五周:[leetCode] 90. Subsets II
- 第十五周 leetcode 77. Combinations(Medium)
- leetcode第十五周解题总结--二分查找(二)
- 第十五周
- 第十五周
- 第十五周
- 2017 前端大事件和趋势回顾,2018 何去何从?
- Centos 和 Linux的区别
- 3-6·yum命令、三步快速搭建yum
- PHP 下载文件到浏览器
- 一些链接
- 第十五周LeetCode
- Bootstrap(三十四)
- 最小单片机系统
- 查看Fedora版本
- java中Buffered读取图片的问题
- SQL的JOIN语句
- 数据库的备份与恢复
- goldengate_mysql_kafka同步
- 多维数组空白字段检测