View Javadoc
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  /**
20   * An edit distance algorithm based on the length of the longest common subsequence between two strings.
21   *
22   * <p>
23   * This code is directly based upon the implementation in {@link LongestCommonSubsequence}.
24   * </p>
25   *
26   * <p>
27   * For reference see: <a href="https://en.wikipedia.org/wiki/Longest_common_subsequence_problem">
28   * https://en.wikipedia.org/wiki/Longest_common_subsequence_problem</a>.
29   * </p>
30   *
31   * <p>For further reading see:</p>
32   *
33   * <p>Lothaire, M. <i>Applied combinatorics on words</i>. New York: Cambridge U Press, 2005. <b>12-13</b></p>
34   *
35   * @since 1.0
36   */
37  public class LongestCommonSubsequenceDistance implements EditDistance<Integer> {
38  
39      /**
40       * Calculates an edit distance between two {@code CharSequence}'s {@code left} and
41       * {@code right} as: {@code left.length() + right.length() - 2 * LCS(left, right)}, where
42       * {@code LCS} is given in {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
43       *
44       * @param left first character sequence
45       * @param right second character sequence
46       * @return distance
47       * @throws IllegalArgumentException
48       *             if either String input {@code null}
49       */
50      @Override
51      public Integer apply(final CharSequence left, final CharSequence right) {
52          // Quick return for invalid inputs
53          if (left == null || right == null) {
54              throw new IllegalArgumentException("Inputs must not be null");
55          }
56          return left.length() + right.length() - 2 * LongestCommonSubsequence.INSTANCE.apply(left, right);
57      }
58  
59  }