Java String Levenshtein Distance levenshtein(String s, String t)

Here you can find the source of levenshtein(String s, String t)

Description

levenshtein

License

Open Source License

Declaration

public static int levenshtein(String s, String t) 

Method Source Code

//package com.java2s;
/***********************************************************************
 *
 * This software is Copyright (C) 2013 Fabio Corubolo - corubolo@gmail.com - and Meriem Bendis
 * The University of Liverpool//ww  w.j a va 2s . c  om
 *
 *
 * BranchingStoryGenerator 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 2 of the License, or
 * (at your option) any later version.
 *
 * BranchingStoryGenerator 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 JavaFF.  If not, see <http://www.gnu.org/licenses/>.
 *
 ************************************************************************/

public class Main {
    public static int levenshtein(String s, String t) {
        /* if either string is empty, difference is inserting all chars 
         * from the other
         */
        if (s.length() == 0)
            return t.length();
        if (t.length() == 0)
            return s.length();

        /* if first letters are the same, the difference is whatever is
         * required to edit the rest of the strings
         */
        if (s.charAt(0) == t.charAt(0))
            return levenshtein(s.substring(1), t.substring(1));

        /* else try:
         *      changing first letter of s to that of t,
         *      remove first letter of s, or
         *      remove first letter of t
         */
        int a = levenshtein(s.substring(1), t.substring(1));
        int b = levenshtein(s, t.substring(1));
        int c = levenshtein(s.substring(1), t);

        if (a > b)
            a = b;
        if (a > c)
            a = c;

        //any of which is 1 edit plus editing the rest of the strings
        return a + 1;
    }
}

Related

  1. levenshtein(final String s1, final String s2)
  2. levenshtein(String str1, String str2)
  3. levenshteinDistance(CharSequence lhs, CharSequence rhs)
  4. levenshteinDistance(CharSequence lhs, CharSequence rhs)
  5. levenshteinDistance(CharSequence s, CharSequence t)