Java String Distance editDistance(String s, String t)

Here you can find the source of editDistance(String s, String t)

Description

The edit distance of the specified <code>String</code>s (see <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance</a>).

License

Open Source License

Parameter

Parameter Description
s a <code>String</code>
t a <code>String</code> witch is compared to <code>o1</code>

Return

the Levenshtein distance

Declaration

public static int editDistance(String s, String t) 

Method Source Code

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

public class Main {
    /**/*from w  ww . ja va 2  s . c o m*/
     * The edit distance of the specified <code>String</code>s (see <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance</a>).
     * @param s a <code>String</code>
     * @param t a <code>String</code> witch is compared to <code>o1</code>
     * @return the Levenshtein distance
     */
    public static int editDistance(String s, String t) {
        int d[][]; // matrix
        int n; // length of s
        int m; // length of t
        int i; // iterates through s
        int j; // iterates through t
        char s_i; // ith character of s
        char t_j; // jth character of t
        int cost; // cost

        n = s.length();
        m = t.length();
        if (n == 0) {
            return m;
        }
        if (m == 0) {
            return n;
        }
        d = new int[n + 1][m + 1];

        for (i = 0; i <= n; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= m; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= n; i++) {

            s_i = s.charAt(i - 1);

            for (j = 1; j <= m; j++) {

                t_j = t.charAt(j - 1);

                if (s_i == t_j) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);

            }

        }

        return d[n][m];

    }

    /**
     * A helper method for <code>editDistance(String, String)</code>.
     * @param a
     * @param b
     * @param c
     * @return the minimum of the given integer
     */
    private static int min(int a, int b, int c) {

        int mi;

        mi = a;

        if (b < mi) {
            mi = b;
        }
        if (c < mi) {
            mi = c;
        }
        return mi;

    }
}

Related

  1. editDistance(CharSequence first, CharSequence second)
  2. editDistance(String one, String two)
  3. editDistance(String s, String t)
  4. editDistance(String s, String t)
  5. editDistance(String s0, String s1)
  6. EditDistance(String s1, String s2)
  7. editDistance(String str1, String str2)
  8. editDistance(String string1, String string2)