Java String Levenshtein Distance levenshteinDistance(CharSequence str1, CharSequence str2)

Here you can find the source of levenshteinDistance(CharSequence str1, CharSequence str2)

Description

NOT CREATED BY ME Shamelessly taken from Wikipedia.

License

Open Source License

Parameter

Parameter Description
str1 The first string.
str2 The second string.

Return

The distance between the two strings as an integer.

Declaration


public static int levenshteinDistance(CharSequence str1, CharSequence str2) 

Method Source Code

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

public class Main {
    /**/*  w ww  .j a v a 2 s.  co  m*/
     * NOT CREATED BY ME
     * Shamelessly taken from Wikipedia. Returns the livenshtein distance of two strings.
     * @param str1 The first string.
     * @param str2 The second string.
     * @return The distance between the two strings as an integer.
     */

    public static int levenshteinDistance(CharSequence str1, CharSequence str2) {
        int[][] distance = new int[str1.length() + 1][str2.length() + 1];

        for (int i = 0; i <= str1.length(); i++)
            distance[i][0] = i;
        for (int j = 1; j <= str2.length(); j++)
            distance[0][j] = j;

        for (int i = 1; i <= str1.length(); i++)
            for (int j = 1; j <= str2.length(); j++)
                distance[i][j] = minimum(distance[i - 1][j] + 1, distance[i][j - 1] + 1,
                        distance[i - 1][j - 1] + ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1));

        return distance[str1.length()][str2.length()];
    }

    private static int minimum(int a, int b, int c) {
        return Math.min(Math.min(a, b), c);
    }
}

Related

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