Java String Distance editDistance(String str1, String str2)

Here you can find the source of editDistance(String str1, String str2)

Description

edit Distance

License

Open Source License

Parameter

Parameter Description
str1 a parameter
str2 a parameter

Declaration

public static double editDistance(String str1, String str2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from  w ww .j  a v a 2  s . co m
     *
     * @param str1
     * @param str2
     * @return
     */
    public static double editDistance(String str1, String str2) {
        int m = str1.length();
        int n = str2.length();
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        int mat[][] = new int[m + 1][n + 1];

        if (m == 0 || n == 0) {
            return Math.max(m, n);
        } else {
            for (int k = 0; k < m + 1; k++) {
                mat[k][0] = k;
            }
            for (int k = 0; k < n + 1; k++) {
                mat[0][k] = k;
            }

            for (int k = 1; k < m + 1; k++) {
                for (int l = 1; l < n + 1; l++) {
                    int cost = 0;
                    if (str1.charAt(k - 1) == str2.charAt(l - 1)) {
                        cost = 0;
                    } else {
                        cost = 1;
                    }
                    mat[k][l] = minimum(mat[k - 1][l] + 1, mat[k][l - 1] + 1, mat[k - 1][l - 1] + cost);
                    if (k > 1 && l > 1 && str1.charAt(k - 1) == str2.charAt(l - 2)
                            && str1.charAt(k - 2) == str2.charAt(l - 1)) {
                        mat[k][l] = Math.min(mat[k][l], mat[k - 2][l - 2] + cost);
                    }
                }

            }
            return mat[m][n];
        }
    }

    private static int minimum(int i, int j, int k) {
        return Math.min(i, Math.min(j, k));
    }
}

Related

  1. editDistance(String s, String t)
  2. editDistance(String s, String t)
  3. editDistance(String s, String t)
  4. editDistance(String s0, String s1)
  5. EditDistance(String s1, String s2)
  6. editDistance(String string1, String string2)
  7. editDistance(String word1, String word2)
  8. Sqr(String[] X)