Java String Distance editDistance(String one, String two)

Here you can find the source of editDistance(String one, String two)

Description

Determine the Levenshtein edit distance between two strings of characters

License

Apache License

Parameter

Parameter Description
one a parameter
two a parameter

Declaration


public static int editDistance(String one, String two) 

Method Source Code

//package com.java2s;
/*/*from w  w  w.j  a  v a 2 s . c o  m*/
   Jaivox version 0.7 March 2014
   Copyright 2010-2014 by Bits and Pixels, Inc.
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
   http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

public class Main {
    /**
     * Determine the Levenshtein edit distance between two strings of characters
     * @param one
     * @param two
     * @return
     */

    public static int editDistance(String one, String two) {
        int n = one.length();
        int m = two.length();
        int[][] distance = new int[n + 1][m + 1];

        for (int i = 0; i <= n; i++)
            distance[i][0] = i;
        for (int j = 0; j <= m; j++)
            distance[0][j] = j;

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                distance[i][j] = minimum(distance[i - 1][j] + 1, distance[i][j - 1] + 1,
                        distance[i - 1][j - 1] + ((one.charAt(i - 1) == two.charAt(j - 1)) ? 0 : 1));
            }
        }

        return distance[n][m];
    }

    /**
     * Used for edit distance
     * @param a
     * @param b
     * @param c
     * @return
     */
    // http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Java
    static int minimum(int a, int b, int c) {
        return Math.min(Math.min(a, b), c);
    }
}

Related

  1. editDistance(CharSequence first, CharSequence second)
  2. editDistance(String s, String t)
  3. editDistance(String s, String t)
  4. editDistance(String s, String t)
  5. editDistance(String s0, String s1)