LeetCode:Edit Distance(字符串编辑距离DP)
2015-08-11 17:22
309 查看
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
简单的状态方程为
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) }
class Solution { public: int minDistance(string word1, string word2) { const int n=word1.size(); const int m=word2.size(); vector<vector<int>> f(n+1,vector<int>(m+1,0)); for(int i=0;i<=n;i++) f[i][0]=i; for(int j=0;j<=m;j++) f[0][j]=j; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(word1[i-1]==word2[j-1]) f[i][j]=f[i-1][j-1]; else{ f[i][j]=min(f[i-1][j-1],min(f[i-1][j],f[i][j-1]))+1; } return f [m]; } };
相关文章推荐
- Android MVVM框架RoboBinding初探
- hdoj-2122 Ice_cream’s world III
- 软件人员推荐书目(一) 大师篇
- 视频流概念
- ListView显示多个的布局
- 【leetcode】209. Minimum Size Subarray Sum
- Handler-简介和用法
- 黑马程序员————反射
- JavaScript基础学习之-javascript权威指南--第八章函数闭包
- 再谈算法复杂度
- JAVA并发编程学习笔记之CAS操作
- Android之Inflate()方法用途
- TI BLE协议栈简介
- win10怎么通过历史记录恢复系统?
- 26-网络编程-09-网络编程(UDP协议-聊天程序)
- Android实例-使用电话拨号器在移动设备上(官方)(XE8+小米2)
- Python中库或者模组的解释
- Caffe下自己的数据训练和测试
- $.ajax 提交数据
- 【VBA研究】生成随机密码