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

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

Description

Levenshtein Distance

License

Apache License

Declaration

public static int LevenshteinDistance(String s, String t) 

Method Source Code

//package com.java2s;
/* //from   w  w w  .j a  va2 s.c o  m
 * Copyright 2016 Lutz Fischer <l.fischer@ed.ac.uk>.
 *
 * 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 {
    public static int LevenshteinDistance(String s, String t) {
        int len_s = s.length();
        int len_t = t.length();
        int last_s = s.length() - 1;
        int last_t = t.length() - 1;
        int cost = 0;

        /* test for degenerate cases of empty strings */
        if (len_s == 0)
            return len_t;
        if (len_t == 0)
            return len_s;

        /* test if last characters of the strings match */
        if (s.charAt(len_s - 1) == t.charAt(len_t - 1))
            cost = 0;
        else
            cost = 1;

        /* return minimum of delete char from s, delete char from t, and delete char from both */
        return Math.min(LevenshteinDistance(s.substring(0, last_s), t) + 1,
                Math.min(LevenshteinDistance(s, t.substring(0, last_t)) + 1,
                        LevenshteinDistance(s.substring(0, last_s), t.substring(0, last_t)) + cost));
    }
}

Related

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