Edit Distance

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

  • Insert a character
  • Delete a character
  • Replace a character

Example:

Input: word1="horse","ros"
Output: 3

Approach

Java

public class EditDistance {
    public static void main(String[] args) {
        String word1 = "horse";
        String word2 = "ros";
        System.out.println(minDistance(word1, word2));
    }

    static int minDistance(String word1String word2) {
        int m = word1.length();
        int n = word2.length();

        // create a 2D array of size (m+1)*(n+1)
        int dp[][] = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                // if first is empty
                if (i == 0)
                    dp[i][j] = j;

                // if second is empty
                else if (j == 0)
                    dp[i][j] = i;
                // if both are same
                else if (word1.charAt(i - 1) == word2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1];

                // else min of insert,delete and replace
                else
                    dp[i][j] = 1 + Math.min(dp[i - 1][j], Math.min(dp[i][j - 1],
                         dp[i - 1][j - 1]));
            }
        }
        return dp[m][n];
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int minDistance(string word1string word2
{
    int m=word1.size(),n=word2.size();

    //create a 2D array of size (m+1)*(n+1)
    int dp[m+1][n+1];
    for(int i=0;i<=m;i++)
        {
           for(int j=0;j<=n;j++)
            {

               //if first is empty
                if(i==0)
                      dp[i][j]=j;

                //if second is empty
                else if(j==0)
                    dp[i][j]=i;
               //if both are same 
                else if(word1[i-1]==word2[j-1])
                      dp[i][j]=dp[i-1][j-1];

                //else min of insert,delete and replace
                else 
                    dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]));
            }
       }
    return dp[m][n];
}
int main()
{
  string word1="horse"word2 = "ros";
  cout<<minDistance(word1,word2);
  return 0;
}


No comments:

Post a Comment