Java Distance Calculate calculateDistance(String firstString, String secondString)

Here you can find the source of calculateDistance(String firstString, String secondString)

Description

Calculate the edit distance between two strings.

License

Open Source License

Parameter

Parameter Description
firstString First given string
secondString Second given string

Return

The edit distance between the two strings, the higher it is the more do they differ

Declaration

private static int calculateDistance(String firstString, String secondString) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   w  w  w. jav a  2s . com
     * Calculate the edit distance between two strings. This method calculates
     * the Levenshtein distance using dynamic programming.
     * 
     * @param firstString
     *            First given string
     * @param secondString
     *            Second given string
     * @return The edit distance between the two strings, the higher it is the
     *         more do they differ
     */
    private static int calculateDistance(String firstString, String secondString) {
        firstString = firstString.toLowerCase();
        secondString = secondString.toLowerCase();

        int[] costs = new int[secondString.length() + 1];
        for (int j = 0; j < costs.length; j++)
            costs[j] = j;
        for (int i = 1; i <= firstString.length(); i++) {
            costs[0] = i;
            int nw = i - 1;
            for (int j = 1; j <= secondString.length(); j++) {
                int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]),
                        firstString.charAt(i - 1) == secondString.charAt(j - 1) ? nw : nw + 1);
                nw = costs[j];
                costs[j] = cj;
            }
        }
        return costs[secondString.length()];
    }
}

Related

  1. calculateDistance(double rssi, double txPower)
  2. calculateDistance(final double x1, final double y1, final double x2, final double y2)
  3. calculateDistance(float[] vec1, float[] vec2)
  4. calculateDistance(int from, int to)
  5. calculateDistance(int x1, int y1, int z1, int x2, int y2, int z2)
  6. calculateDistanceBetween(double sourceLatitude, double sourceLongitude, double destinationLatitude, double destinationLongitude)
  7. calculateDistanceInKm(double lat1, double lon1, double lat2, double lon2)
  8. calculateDistanceNoNormalization(float[] vec1, float[] vec2)
  9. calculateDistancePointToShowerAxis(double cogx, double cogy, double delta, double x, double y)