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. <em>Applied combinatorics on words</em>. New York: Cambridge U Press, 2005. <strong>12-13</strong></p>
  33.  *
  34.  * @since 1.0
  35.  */
  36. public class LongestCommonSubsequenceDistance implements EditDistance<Integer> {

  37.     /**
  38.      * Creates a new instance.
  39.      */
  40.     public LongestCommonSubsequenceDistance() {
  41.         // empty
  42.     }

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

  62. }