LevenshteinDistance.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.text.similarity;

  18. import java.util.Arrays;

  19. /**
  20.  * An algorithm for measuring the difference between two character sequences.
  21.  *
  22.  * <p>
  23.  * This is the number of changes needed to change one sequence into another,
  24.  * where each change is a single character modification (deletion, insertion
  25.  * or substitution).
  26.  * </p>
  27.  *
  28.  * <p>
  29.  * This code has been adapted from Apache Commons Lang 3.3.
  30.  * </p>
  31.  *
  32.  * @since 1.0
  33.  */
  34. public class LevenshteinDistance implements EditDistance<Integer> {

  35.     /**
  36.      * Default instance.
  37.      */
  38.     private static final LevenshteinDistance DEFAULT_INSTANCE = new LevenshteinDistance();

  39.     /**
  40.      * Threshold.
  41.      */
  42.     private final Integer threshold;

  43.     /**
  44.      * <p>
  45.      * This returns the default instance that uses a version
  46.      * of the algorithm that does not use a threshold parameter.
  47.      * </p>
  48.      *
  49.      * @see LevenshteinDistance#getDefaultInstance()
  50.      */
  51.     public LevenshteinDistance() {
  52.         this(null);
  53.     }

  54.     /**
  55.      * <p>
  56.      * If the threshold is not null, distance calculations will be limited to a maximum length.
  57.      * If the threshold is null, the unlimited version of the algorithm will be used.
  58.      * </p>
  59.      *
  60.      * @param threshold
  61.      *        If this is null then distances calculations will not be limited.
  62.      *        This may not be negative.
  63.      */
  64.     public LevenshteinDistance(final Integer threshold) {
  65.         if (threshold != null && threshold < 0) {
  66.             throw new IllegalArgumentException("Threshold must not be negative");
  67.         }
  68.         this.threshold = threshold;
  69.     }

  70.     /**
  71.      * <p>Find the Levenshtein distance between two Strings.</p>
  72.      *
  73.      * <p>A higher score indicates a greater distance.</p>
  74.      *
  75.      * <p>The previous implementation of the Levenshtein distance algorithm
  76.      * was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
  77.      *
  78.      * <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
  79.      * which can occur when my Java implementation is used with very large strings.<br>
  80.      * This implementation of the Levenshtein distance algorithm
  81.      * is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
  82.      *
  83.      * <pre>
  84.      * distance.apply(null, *)             = IllegalArgumentException
  85.      * distance.apply(*, null)             = IllegalArgumentException
  86.      * distance.apply("","")               = 0
  87.      * distance.apply("","a")              = 1
  88.      * distance.apply("aaapppp", "")       = 7
  89.      * distance.apply("frog", "fog")       = 1
  90.      * distance.apply("fly", "ant")        = 3
  91.      * distance.apply("elephant", "hippo") = 7
  92.      * distance.apply("hippo", "elephant") = 7
  93.      * distance.apply("hippo", "zzzzzzzz") = 8
  94.      * distance.apply("hello", "hallo")    = 1
  95.      * </pre>
  96.      *
  97.      * @param left the first string, must not be null
  98.      * @param right the second string, must not be null
  99.      * @return result distance, or -1
  100.      * @throws IllegalArgumentException if either String input {@code null}
  101.      */
  102.     @Override
  103.     public Integer apply(final CharSequence left, final CharSequence right) {
  104.         if (threshold != null) {
  105.             return limitedCompare(left, right, threshold);
  106.         }
  107.         return unlimitedCompare(left, right);
  108.     }

  109.     /**
  110.      * Gets the default instance.
  111.      *
  112.      * @return the default instace
  113.      */
  114.     public static LevenshteinDistance getDefaultInstance() {
  115.         return DEFAULT_INSTANCE;
  116.     }

  117.     /**
  118.      * Gets the distance threshold.
  119.      *
  120.      * @return the distance threshold
  121.      */
  122.     public Integer getThreshold() {
  123.         return threshold;
  124.     }

  125.     /**
  126.      * Find the Levenshtein distance between two CharSequences if it's less than or
  127.      * equal to a given threshold.
  128.      *
  129.      * <p>
  130.      * This implementation follows from Algorithms on Strings, Trees and
  131.      * Sequences by Dan Gusfield and Chas Emerick's implementation of the
  132.      * Levenshtein distance algorithm from <a
  133.      * href="http://www.merriampark.com/ld.htm"
  134.      * >http://www.merriampark.com/ld.htm</a>
  135.      * </p>
  136.      *
  137.      * <pre>
  138.      * limitedCompare(null, *, *)             = IllegalArgumentException
  139.      * limitedCompare(*, null, *)             = IllegalArgumentException
  140.      * limitedCompare(*, *, -1)               = IllegalArgumentException
  141.      * limitedCompare("","", 0)               = 0
  142.      * limitedCompare("aaapppp", "", 8)       = 7
  143.      * limitedCompare("aaapppp", "", 7)       = 7
  144.      * limitedCompare("aaapppp", "", 6))      = -1
  145.      * limitedCompare("elephant", "hippo", 7) = 7
  146.      * limitedCompare("elephant", "hippo", 6) = -1
  147.      * limitedCompare("hippo", "elephant", 7) = 7
  148.      * limitedCompare("hippo", "elephant", 6) = -1
  149.      * </pre>
  150.      *
  151.      * @param left the first string, must not be null
  152.      * @param right the second string, must not be null
  153.      * @param threshold the target threshold, must not be negative
  154.      * @return result distance, or -1
  155.      */
  156.     private static int limitedCompare(CharSequence left, CharSequence right, final int threshold) { // NOPMD
  157.         if (left == null || right == null) {
  158.             throw new IllegalArgumentException("Strings must not be null");
  159.         }
  160.         if (threshold < 0) {
  161.             throw new IllegalArgumentException("Threshold must not be negative");
  162.         }

  163.         /*
  164.          * This implementation only computes the distance if it's less than or
  165.          * equal to the threshold value, returning -1 if it's greater. The
  166.          * advantage is performance: unbounded distance is O(nm), but a bound of
  167.          * k allows us to reduce it to O(km) time by only computing a diagonal
  168.          * stripe of width 2k + 1 of the cost table. It is also possible to use
  169.          * this to compute the unbounded Levenshtein distance by starting the
  170.          * threshold at 1 and doubling each time until the distance is found;
  171.          * this is O(dm), where d is the distance.
  172.          *
  173.          * One subtlety comes from needing to ignore entries on the border of
  174.          * our stripe eg. p[] = |#|#|#|* d[] = *|#|#|#| We must ignore the entry
  175.          * to the left of the leftmost member We must ignore the entry above the
  176.          * rightmost member
  177.          *
  178.          * Another subtlety comes from our stripe running off the matrix if the
  179.          * strings aren't of the same size. Since string s is always swapped to
  180.          * be the shorter of the two, the stripe will always run off to the
  181.          * upper right instead of the lower left of the matrix.
  182.          *
  183.          * As a concrete example, suppose s is of length 5, t is of length 7,
  184.          * and our threshold is 1. In this case we're going to walk a stripe of
  185.          * length 3. The matrix would look like so:
  186.          *
  187.          * <pre>
  188.          *    1 2 3 4 5
  189.          * 1 |#|#| | | |
  190.          * 2 |#|#|#| | |
  191.          * 3 | |#|#|#| |
  192.          * 4 | | |#|#|#|
  193.          * 5 | | | |#|#|
  194.          * 6 | | | | |#|
  195.          * 7 | | | | | |
  196.          * </pre>
  197.          *
  198.          * Note how the stripe leads off the table as there is no possible way
  199.          * to turn a string of length 5 into one of length 7 in edit distance of
  200.          * 1.
  201.          *
  202.          * Additionally, this implementation decreases memory usage by using two
  203.          * single-dimensional arrays and swapping them back and forth instead of
  204.          * allocating an entire n by m matrix. This requires a few minor
  205.          * changes, such as immediately returning when it's detected that the
  206.          * stripe has run off the matrix and initially filling the arrays with
  207.          * large values so that entries we don't compute are ignored.
  208.          *
  209.          * See Algorithms on Strings, Trees and Sequences by Dan Gusfield for
  210.          * some discussion.
  211.          */

  212.         int n = left.length(); // length of left
  213.         int m = right.length(); // length of right

  214.         // if one string is empty, the edit distance is necessarily the length
  215.         // of the other
  216.         if (n == 0) {
  217.             return m <= threshold ? m : -1;
  218.         } else if (m == 0) {
  219.             return n <= threshold ? n : -1;
  220.         }

  221.         if (n > m) {
  222.             // swap the two strings to consume less memory
  223.             final CharSequence tmp = left;
  224.             left = right;
  225.             right = tmp;
  226.             n = m;
  227.             m = right.length();
  228.         }

  229.         int[] p = new int[n + 1]; // 'previous' cost array, horizontally
  230.         int[] d = new int[n + 1]; // cost array, horizontally
  231.         int[] tempD; // placeholder to assist in swapping p and d

  232.         // fill in starting table values
  233.         final int boundary = Math.min(n, threshold) + 1;
  234.         for (int i = 0; i < boundary; i++) {
  235.             p[i] = i;
  236.         }
  237.         // these fills ensure that the value above the rightmost entry of our
  238.         // stripe will be ignored in following loop iterations
  239.         Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
  240.         Arrays.fill(d, Integer.MAX_VALUE);

  241.         // iterates through t
  242.         for (int j = 1; j <= m; j++) {
  243.             final char rightJ = right.charAt(j - 1); // jth character of right
  244.             d[0] = j;

  245.             // compute stripe indices, constrain to array size
  246.             final int min = Math.max(1, j - threshold);
  247.             final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(
  248.                     n, j + threshold);

  249.             // the stripe may lead off of the table if s and t are of different
  250.             // sizes
  251.             if (min > max) {
  252.                 return -1;
  253.             }

  254.             // ignore entry left of leftmost
  255.             if (min > 1) {
  256.                 d[min - 1] = Integer.MAX_VALUE;
  257.             }

  258.             // iterates through [min, max] in s
  259.             for (int i = min; i <= max; i++) {
  260.                 if (left.charAt(i - 1) == rightJ) {
  261.                     // diagonally left and up
  262.                     d[i] = p[i - 1];
  263.                 } else {
  264.                     // 1 + minimum of cell to the left, to the top, diagonally
  265.                     // left and up
  266.                     d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]);
  267.                 }
  268.             }

  269.             // copy current distance counts to 'previous row' distance counts
  270.             tempD = p;
  271.             p = d;
  272.             d = tempD;
  273.         }

  274.         // if p[n] is greater than the threshold, there's no guarantee on it
  275.         // being the correct
  276.         // distance
  277.         if (p[n] <= threshold) {
  278.             return p[n];
  279.         }
  280.         return -1;
  281.     }

  282.     /**
  283.      * <p>Find the Levenshtein distance between two Strings.</p>
  284.      *
  285.      * <p>A higher score indicates a greater distance.</p>
  286.      *
  287.      * <p>The previous implementation of the Levenshtein distance algorithm
  288.      * was from <a href="https://web.archive.org/web/20120526085419/http://www.merriampark.com/ldjava.htm">
  289.      * https://web.archive.org/web/20120526085419/http://www.merriampark.com/ldjava.htm</a></p>
  290.      *
  291.      * <p>This implementation only need one single-dimensional arrays of length s.length() + 1</p>
  292.      *
  293.      * <pre>
  294.      * unlimitedCompare(null, *)             = IllegalArgumentException
  295.      * unlimitedCompare(*, null)             = IllegalArgumentException
  296.      * unlimitedCompare("","")               = 0
  297.      * unlimitedCompare("","a")              = 1
  298.      * unlimitedCompare("aaapppp", "")       = 7
  299.      * unlimitedCompare("frog", "fog")       = 1
  300.      * unlimitedCompare("fly", "ant")        = 3
  301.      * unlimitedCompare("elephant", "hippo") = 7
  302.      * unlimitedCompare("hippo", "elephant") = 7
  303.      * unlimitedCompare("hippo", "zzzzzzzz") = 8
  304.      * unlimitedCompare("hello", "hallo")    = 1
  305.      * </pre>
  306.      *
  307.      * @param left the first String, must not be null
  308.      * @param right the second String, must not be null
  309.      * @return result distance, or -1
  310.      * @throws IllegalArgumentException if either String input {@code null}
  311.      */
  312.     private static int unlimitedCompare(CharSequence left, CharSequence right) {
  313.         if (left == null || right == null) {
  314.             throw new IllegalArgumentException("Strings must not be null");
  315.         }

  316.         /*
  317.            This implementation use two variable to record the previous cost counts,
  318.            So this implementation use less memory than previous impl.
  319.          */

  320.         int n = left.length(); // length of left
  321.         int m = right.length(); // length of right

  322.         if (n == 0) {
  323.             return m;
  324.         } else if (m == 0) {
  325.             return n;
  326.         }

  327.         if (n > m) {
  328.             // swap the input strings to consume less memory
  329.             final CharSequence tmp = left;
  330.             left = right;
  331.             right = tmp;
  332.             n = m;
  333.             m = right.length();
  334.         }

  335.         int[] p = new int[n + 1];

  336.         // indexes into strings left and right
  337.         int i; // iterates through left
  338.         int j; // iterates through right
  339.         int upper_left;
  340.         int upper;

  341.         char rightJ; // jth character of right
  342.         int cost; // cost

  343.         for (i = 0; i <= n; i++) {
  344.             p[i] = i;
  345.         }

  346.         for (j = 1; j <= m; j++) {
  347.             upper_left = p[0];
  348.             rightJ = right.charAt(j - 1);
  349.             p[0] = j;

  350.             for (i = 1; i <= n; i++) {
  351.                 upper = p[i];
  352.                 cost = left.charAt(i - 1) == rightJ ? 0 : 1;
  353.                 // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
  354.                 p[i] = Math.min(Math.min(p[i - 1] + 1, p[i] + 1), upper_left + cost);
  355.                 upper_left = upper;
  356.             }
  357.         }

  358.         return p[n];
  359.     }

  360. }