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
Analysis:
public int minDistance(String word1, String word2) { int s1 = word1.length(); int s2 = word2.length(); if(s1 == 0) return s2; if(s2 == 0) return s1; int [][]dis = new int[s1+1][s2+1]; for(int i=0;i<=s1;i++)//init condition dis[i][0] = i; for(int i=0;i<=s2;i++) dis[0][i] = i; for(int i=1;i<=s1;i++){ for(int j=1;j<=s2;j++){ if(word1.charAt(i-1)==word2.charAt(j-1)){ dis[i][j] = dis[i-1][j-1]; }else { int temp = Math.min(dis[i-1][j], dis[i][j-1]); dis[i][j] = Math.min(dis[i-1][j-1], temp)+1; } } } return dis[s1][s2]; }c++
int minDistance(string word1, string word2) { int s1 = word1.size(); int s2 = word2.size(); if(s1 == 0) return s2; if(s2 == 0) return s1; vector<int> *dp = new vector<int>[s2+1]; for(int i=0;i<=s1;i++) dp[0].push_back(i); for(int i=0;i<=s2;i++) dp[i].push_back(i); for(int i=1;i<=s2;i++){ for(int j=1;j<=s1;j++){ int n1 = word2[i-1]!=word1[j-1]?(dp[i-1][j-1]+1):dp[i-1][j-1]; int n2 = dp[i-1][j]<dp[i][j-1]?(dp[i-1][j]+1):(dp[i][j-1]+1); dp[i].push_back(n1<n2? n1:n2); } } return dp[s2][s1]; }