Java String Levenshtein Distance levenshteinDistance(CharSequence s, CharSequence t)

Here you can find the source of levenshteinDistance(CharSequence s, CharSequence t)

Description

Find the Levenshtein distance between two Strings.

License

Open Source License

Parameter

Parameter Description
s the first String, must not be null
t the second String, must not be null

Return

result distance

Declaration

public static int levenshteinDistance(CharSequence s, CharSequence t) 

Method Source Code

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

public class Main {
    /**/*from  ww w  .j a  va  2  s . co m*/
     * Find the Levenshtein distance between two Strings.
     * 
     * This is the number of changes needed to change one String into another,
     * where each change is a single character modification (deletion, insertion or substitution).
     * 
     * @param s
     *            the first String, must not be null
     * @param t
     *            the second String, must not be null
     * @return result distance
     */
    public static int levenshteinDistance(CharSequence s, CharSequence t) {
        if (s == null || t == null)
            throw new IllegalArgumentException("Strings must not be null");

        int n = s.length();
        int m = t.length();

        if (n == 0)
            return m;
        else if (m == 0)
            return n;

        if (n > m) {
            final CharSequence tmp = s;
            s = t;
            t = tmp;
            n = m;
            m = t.length();
        }

        int p[] = new int[n + 1];
        int d[] = new int[n + 1];
        int _d[];

        int i;
        int j;

        char t_j;

        int cost;

        for (i = 0; i <= n; i++)
            p[i] = i;

        for (j = 1; j <= m; j++) {
            t_j = t.charAt(j - 1);
            d[0] = j;

            for (i = 1; i <= n; i++) {
                cost = s.charAt(i - 1) == t_j ? 0 : 1;
                d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
            }

            _d = p;
            p = d;
            d = _d;
        }

        return p[n];
    }
}

Related

  1. levenshtein(final String s1, final String s2)
  2. levenshtein(String s, String t)
  3. levenshtein(String str1, String str2)
  4. levenshteinDistance(CharSequence lhs, CharSequence rhs)
  5. levenshteinDistance(CharSequence lhs, CharSequence rhs)
  6. levenshteinDistance(CharSequence str1, CharSequence str2)
  7. levenshteinDistance(final String string1, final String string2, int swap, int substitution, int insertion, int deletion)
  8. LevenshteinDistance(String actual, String expected)
  9. levenshteinDistance(String s, String t)