Java String Levenshtein Distance LevenshteinDistance(String actual, String expected)

Here you can find the source of LevenshteinDistance(String actual, String expected)

Description

Levenshtein Distance

License

Open Source License

Declaration

private static int LevenshteinDistance(String actual, String expected) 

Method Source Code

//package com.java2s;

public class Main {
    private static int LevenshteinDistance(String actual, String expected) {

        //char s[1..m], char t[1..n])
        String s[] = actual.split("\\s+");
        String t[] = expected.split("\\s+");

        //for (int i=0;i<s.length;i++) {
        //   _logger.info(i+" "+s[i]);
        //}/* w ww  .j a v a2s.  c o  m*/

        //int count =0;
        //for (String x: t ) {
        //   _logger.info(count++ +" "+x);
        //}

        // d is a table with m+1 rows and n+1 columns
        int[][] d = new int[s.length + 1][t.length + 1];

        for (int i = 0; i <= s.length; i++) {
            d[i][0] = i;
        }
        for (int j = 0; j <= t.length; j++) {
            d[0][j] = j;
        }

        int cost = 0;
        for (int i = 1; i <= s.length; i++) {
            for (int j = 1; j <= t.length; j++) {
                if (s[i - 1].equals(t[j - 1])) {
                    cost = 0;
                } else {
                    cost = 1;
                }
                int del = d[i - 1][j] + 1;
                int ins = d[i][j - 1] + 1;
                int sub = d[i - 1][j - 1] + cost;
                if ((del < ins) && (del < sub)) {
                    d[i][j] = del;
                } else if ((ins < del) && (ins < sub)) { //could eliminate first check...
                    d[i][j] = ins;
                } else {
                    d[i][j] = sub;
                }
            }
        }
        return d[s.length][t.length];
    }
}

Related

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