Android String Levenshtein Distance Get computeLevenshteinDistance(CharSequence str1, CharSequence str2)

Here you can find the source of computeLevenshteinDistance(CharSequence str1, CharSequence str2)

Description

compute Levenshtein Distance

Declaration

public static int computeLevenshteinDistance(CharSequence str1,
            CharSequence str2) 

Method Source Code

//package com.java2s;

public class Main {
    public static int computeLevenshteinDistance(CharSequence str1,
            CharSequence str2) {//from  w ww.j  av  a  2s  .  c om

        int commonPrefixLength = findCommonPrefixLength(str1, str2);

        if (commonPrefixLength == str1.length()
                && commonPrefixLength == str2.length()) {
            return 0; // same exact string
        }

        int commonSuffixLength = findCommonSuffixLength(str1, str2,
                commonPrefixLength);

        str1 = str1.subSequence(commonPrefixLength, str1.length()
                - commonSuffixLength);
        str2 = str2.subSequence(commonPrefixLength, str2.length()
                - commonSuffixLength);

        int[][] distance = new int[str1.length() + 1][str2.length() + 1];

        for (int i = 0; i <= str1.length(); i++) {
            distance[i][0] = i;
        }
        for (int j = 0; j <= str2.length(); j++) {
            distance[0][j] = j;
        }

        for (int i = 1; i <= str1.length(); i++) {
            for (int j = 1; j <= str2.length(); j++) {
                distance[i][j] = minimum(
                        distance[i - 1][j] + 1,
                        distance[i][j - 1] + 1,
                        distance[i - 1][j - 1]
                                + ((str1.charAt(i - 1) == str2
                                        .charAt(j - 1)) ? 0 : 1));
            }
        }

        int dist = distance[str1.length()][str2.length()];

        return dist;
    }

    private static int findCommonPrefixLength(CharSequence str1,
            CharSequence str2) {

        int length = (Math.min(str1.length(), str2.length()));
        for (int i = 0; i < length; i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                return i;
            }
        }

        return 0;

    }

    private static int findCommonSuffixLength(CharSequence str1,
            CharSequence str2, int commonPrefixLength) {
        int length = (Math.min(str1.length(), str2.length()));
        for (int i = 0; i < length - commonPrefixLength; i++) {
            if (str1.charAt(str1.length() - i - 1) != str2.charAt(str2
                    .length() - i - 1)) {
                return i;
            }
        }

        return 0;
    }

    private static int minimum(int a, int b, int c) {
        return Math.min(Math.min(a, b), c);
    }
}