Solution 1:

m[i][j] min edit distance in order to make substring (0 - i) equal to substring(0, j)

base case:

   m[0][j] = j

   m[i][0] = i

induction rule:

  m[i][j] = 1 + min(m[i-1][j-1](replace),m[i-1][j](delete),m[i][j-1](insert))  when one[i - 1] != two[j - 1]

  m[i][j] = m[i-1][j-1] when one[i - 1] == two[j - 1]
public class Solution {
  public int editDistance(String one, String two) {
    // Write your solution here.
    if (one.length() == 0 && two.length() == 0) {
      return 0;
    } else if (one.length() != 0 && two.length() == 0) {
      return one.length();
    } else if (one.length() == 0 && two.length() != 0) {
      return two.length();
    }
    // m[i][j] min edit distance in order to make substring (0 - i) to substring(0, j) equal 
    // m[i][j] = 1 + min(m[i-1][j-1](replace),m[i-1][j]()(delete),m[i][j-1](insert))
    int[][] m = new int[one.length() + 1][two.length() + 1];
    for (int i = 0; i <= one.length(); i++) {
      for(int j = 0; j <= two.length(); j++) {
        if (i == 0) {
          m[i][j] = j;
        } else if(j == 0) {
          m[i][j] = i;
        } else if(one.charAt(i-1) == two.charAt(j-1)) {
          m[i][j] = m[i-1][j-1];
        }else {
          m[i][j] = Math.min(m[i - 1][j - 1], m[i - 1][j]) + 1;
          m[i][j] = Math.min(m[i][j-1] + 1, m[i][j]);
        }
      }
    }
    return m[one.length()][two.length()];
  }

}

Solution 2:

public int editDistance(String one, String two) {
    // Write your solution here.
    if (one.length() == 0 && two.length() == 0) {
      return 0;
    } else if (one.length() != 0 && two.length() == 0) {
      return one.length();
    } else if (one.length() == 0 && two.length() != 0) {
      return two.length();
    }

    return helper(one, 0, two, 0);
}
private int helper(String one, int index1, String two, int index2) {
if (index1 == one.length()) return two.length() - index2;
if (index2 == two.length()) return one.length() - index1;
if (one.charAt(index1) == two.charAt(index2)) {
return helper(one,index1 + 1, two, index2 + 1);
}
int replace = 1 + helper(one, index1 + 1, two, index2 + 1);
int delete = 1 + helper(one,index1 + 1, two, index2);
int insert = 1 + helper(one, index1, two, index2 + 1);
return Math.min(Math.min(replace,delete),insert);
}

results matching ""

    No results matching ""