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