Java String Levenshtein Distance levenshteinDistance(String string1, String string2)

Here you can find the source of levenshteinDistance(String string1, String string2)

Description

levenshtein Distance

License

Open Source License

Declaration

public static int levenshteinDistance(String string1, String string2) 

Method Source Code

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

public class Main {
    public static int levenshteinDistance(String string1, String string2) {
        char[] s1 = string1.toCharArray();
        char[] s2 = string2.toCharArray();
        int n1 = s1.length;
        int n2 = s2.length;
        int[][] d = new int[n1 + 1][n2 + 1];
        for (int i = 1; i < n1 + 1; i++) {
            d[i][0] = i;//  w ww  . ja v  a 2 s . co m
        }
        for (int j = 1; j < n2 + 1; j++) {
            d[0][j] = j;
        }
        for (int j = 0; j < n2; j++) {
            for (int i = 0; i < n1; i++) {
                int substitutionCost;
                if (s1[i] == s2[j]) {
                    substitutionCost = 0;
                } else {
                    substitutionCost = 1;
                }
                d[i + 1][j + 1] = Math.min(Math.min(d[i][j + 1] + 1, d[i + 1][j] + 1), d[i][j] + substitutionCost);
            }
        }
        return d[n1][n2];
    }
}

Related

  1. levenshteinDistance(String s, String t)
  2. levenshteinDistance(String s, String t, int limit)
  3. levenshteinDistance(String s1, String s2)
  4. levenshteinDistance(String s1, String s2)
  5. levenshteinDistance(String st1, String st2)
  6. levenshteinDistance(String wordForm, String lemma)
  7. levenshteinDistance(String x, String y)
  8. levenshteinDistance(String[] a, String[] b)
  9. levenshteinDistanceRatio(CharSequence lhs, CharSequence rhs)