LongestCommonSubsequenceDistance.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. /**
  19.  * An edit distance algorithm based on the length of the longest common subsequence between two strings.
  20.  *
  21.  * <p>
  22.  * This code is directly based upon the implementation in {@link LongestCommonSubsequence}.
  23.  * </p>
  24.  *
  25.  * <p>
  26.  * For reference see: <a href="https://en.wikipedia.org/wiki/Longest_common_subsequence_problem">
  27.  * https://en.wikipedia.org/wiki/Longest_common_subsequence_problem</a>.
  28.  * </p>
  29.  *
  30.  * <p>For further reading see:</p>
  31.  *
  32.  * <p>Lothaire, M. <i>Applied combinatorics on words</i>. New York: Cambridge U Press, 2005. <b>12-13</b></p>
  33.  *
  34.  * @since 1.0
  35.  */
  36. public class LongestCommonSubsequenceDistance implements EditDistance<Integer> {

  37.     private final LongestCommonSubsequence longestCommonSubsequence = new LongestCommonSubsequence();

  38.     /**
  39.      * Calculates an edit distance between two <code>CharSequence</code>'s <code>left</code> and
  40.      * <code>right</code> as: <code>left.length() + right.length() - 2 * LCS(left, right)</code>, where
  41.      * <code>LCS</code> is given in {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
  42.      *
  43.      * @param left first character sequence
  44.      * @param right second character sequence
  45.      * @return distance
  46.      * @throws IllegalArgumentException
  47.      *             if either String input {@code null}
  48.      */
  49.     @Override
  50.     public Integer apply(final CharSequence left, final CharSequence right) {
  51.         // Quick return for invalid inputs
  52.         if (left == null || right == null) {
  53.             throw new IllegalArgumentException("Inputs must not be null");
  54.         }
  55.         return left.length() + right.length() - 2 * longestCommonSubsequence.apply(left, right);
  56.     }

  57. }