Java String Distance editDistance(CharSequence first, CharSequence second)

Here you can find the source of editDistance(CharSequence first, CharSequence second)

Description

Returns the edit distance of the two CharSequences.
Uses Levenshtein algorithm.

License

Open Source License

Parameter

Parameter Description
first a parameter
second a parameter

Return

distance

Declaration

public static int editDistance(CharSequence first, CharSequence second) 

Method Source Code

//package com.java2s;
/**/*from   www.  j  a va2 s  .c om*/
 * Stringter: Workbench for string editing
 *
 * Copyright (C) 2015 Zdravko Petkov
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Returns the edit distance of the two CharSequences.<br>
     * Uses Levenshtein algorithm.
     *
     * @param first
     * @param second
     * @return distance
     */
    public static int editDistance(CharSequence first, CharSequence second) {
        int firstLength = first.length();
        int secondLength = second.length();
        int[][] distance = new int[firstLength + 1][secondLength + 1];
        for (int f = 0; f <= firstLength; f++) {
            distance[f][0] = f;
        }
        for (int s = 0; s <= secondLength; s++) {
            distance[0][s] = s;
        }
        for (int i = 1; i <= firstLength; i++) {
            for (int j = 1; j <= secondLength; j++) {
                if (first.charAt(i - 1) == second.charAt(j - 1)) {
                    distance[i][j] = distance[i - 1][j - 1];
                } else {
                    int delete = distance[i][j - 1] + 1;
                    int insert = distance[i - 1][j] + 1;
                    int replace = distance[i - 1][j - 1] + 1;
                    distance[i][j] = Math.min(Math.min(delete, insert), replace);
                }
            }
        }

        return distance[firstLength][secondLength];
    }
}

Related

  1. editDistance(String one, String two)
  2. editDistance(String s, String t)
  3. editDistance(String s, String t)
  4. editDistance(String s, String t)