LeetCode:Edit Distance(字符串编辑距离DP)
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<vector<int>> f(n+1,vector<int>(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 };