Derived from pseudocode at: http://en.wikipedia.org/wiki/Levenshtein_distance Used to determine edit distances between two strings - Java java.lang

Java examples for java.lang:String Algorithm

Description

Derived from pseudocode at: http://en.wikipedia.org/wiki/Levenshtein_distance Used to determine edit distances between two strings

Demo Code

/*/*www . j av a  2s . c  om*/
 **    Copyright (C) 2003-2012 Institute for Systems Biology 
 **                            Seattle, Washington, USA. 
 **
 **    This library is free software; you can redistribute it and/or
 **    modify it under the terms of the GNU Lesser General Public
 **    License as published by the Free Software Foundation; either
 **    version 2.1 of the License, or (at your option) any later version.
 **
 **    This library 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
 **    Lesser General Public License for more details.
 **
 **    You should have received a copy of the GNU Lesser General Public
 **    License along with this library; if not, write to the Free Software
 **    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
//package com.java2s;

public class Main {
    /***************************************************************************
     **
     ** Derived from pseudocode at: http://en.wikipedia.org/wiki/Levenshtein_distance
     ** Used to determine edit distances between two strings
     */

    public static int levenshteinDistance(String s, String t) {

        int m = s.length();
        int n = t.length();

        int dtable[][] = new int[m + 1][n + 1];

        for (int i = 0; i <= m; i++) {
            dtable[i][0] = i; // deletion
        }

        for (int j = 0; j <= n; j++) {
            dtable[0][j] = j; // insertion
        }

        for (int j = 1; j <= n; j++) {
            for (int i = 1; i <= m; i++) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    dtable[i][j] = dtable[i - 1][j - 1];
                } else {
                    int delDist = dtable[i - 1][j] + 1; // deletion
                    int insDist = dtable[i][j - 1] + 1; // insertion
                    int subDist = dtable[i - 1][j - 1] + 1; // substitution
                    dtable[i][j] = Math.min(Math.min(delDist, insDist),
                            subDist);
                }
            }
        }

        return (dtable[m][n]);
    }
}

Related Tutorials