Given 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
Topic:
Given two strings, the minimum number of operands required to change s to T.
3 character operations are insert, delete, and replace, respectively.
Ideas:
Dynamic Planning Ideas:
Suppose Dp[i][j] represents the minimum number of operands required to convert a string ending with s[i] and a string ending with t[j], consider three operations, and then take the three minimum values:
1. Replacement:
Assuming S[i-1],t[j-1] is aligned, i.e. Dp[i-1][j-1] is known, then when S[i]==t[j], dp[i][j]=dp[i-1][j-1], otherwise, dp[i][j]=dp[i-1][j-1]+1.
2. Delete
Suppose S[i-1],t[j] is aligned, that is, Dp[i-1][j] is known, the extra s[i] needs to be deleted, the operand +1, then dp[i][j]=dp[i-1][j]+1.
3. Insert
Suppose S[i],t[j-1] is aligned, i.e. Dp[i][j-1] is known, it needs to be inserted in S s[i+1]=t[j] to match, operand +1, then dp[i][j]=dp[i][j-1]+1.
State transition equation:
Dp[i][j]=min (dp[i-1][j-1]+ (s[i]==t[j]?0,1), dp[i-1][j]+1,dp[i][j-1]+1)
Initial value:
Dp[i][0]=i
Dp[0][j]=j
Complexity of:
Complexity of Time: O (m*n)
Space complexity: O (M*n)
Space optimization:
By the state transfer equation, dp[i][j] and dp[i-1][j-1],dp[i-1][j],dp[i][j-1], can be removed one dimension, leaving only Dp[j].
The dp[i-1][j] and dp[i][j-1] on the right of the equation can be changed directly to Dp[j] (old values) and Dp[j-1] (updated), and only Dp[i-1][j-1] is not recorded, and can be saved by a variable.
So space complexity: O (N)
Code:
class Solution {public:int mindistance (string word1, String word2) {int m= Word1.length (); int N=word2.length (); vector<vector<int> > Distance (m+1,vector<int> (n+1)); for (int i=0;i<=m;i++) {for (int j=0;j<=n;j++) {if (0==i) {distance[i][j]= J } else if (0==j) {distance[i][j]=i; } else{Distance[i][j]=min (distance[i-1][j-1]+ (word1[i-1]==word2[j-1])? 0:1), Min (distance[i-1][j]+1,distance[i][j-1]+1)); }}} return distance[m][n]; }};
Class Solution {public: int mindistance (string word1, String word2) { int m=word1.length (); int n=word2.length (); Vector<int> distance (n+1); for (int i=0;i<=m;i++) { int last; for (int j=0;j<=n;j++) { if (0==i) { distance[j]=j; } else if (0==j) { last=distance[j]; distance[j]=i; } else{ int temp=distance[j]; Distance[j]=min (last+ (word1[i-1]==word2[j-1]) 0:1), min (distance[j]+1,distance[j-1]+1) ); Last=temp ; }}} return distance[n];} ;
(Leetcode) Edit Distance