001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.text.similarity;
018
019/**
020 * An edit distance algorithm based on the length of the longest common subsequence between two strings.
021 *
022 * <p>
023 * This code is directly based upon the implementation in {@link LongestCommonSubsequence}.
024 * </p>
025 *
026 * <p>
027 * For reference see: <a href="https://en.wikipedia.org/wiki/Longest_common_subsequence_problem">
028 * https://en.wikipedia.org/wiki/Longest_common_subsequence_problem</a>.
029 * </p>
030 *
031 * <p>For further reading see:</p>
032 *
033 * <p>Lothaire, M. <i>Applied combinatorics on words</i>. New York: Cambridge U Press, 2005. <b>12-13</b></p>
034 *
035 * @since 1.0
036 */
037public class LongestCommonSubsequenceDistance implements EditDistance<Integer> {
038
039    /**
040     * Object for calculating the longest common subsequence that we can then normalize in apply.
041     */
042    private final LongestCommonSubsequence longestCommonSubsequence = new LongestCommonSubsequence();
043
044    /**
045     * Calculates an edit distance between two {@code CharSequence}'s {@code left} and
046     * {@code right} as: {@code left.length() + right.length() - 2 * LCS(left, right)}, where
047     * {@code LCS} is given in {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
048     *
049     * @param left first character sequence
050     * @param right second character sequence
051     * @return distance
052     * @throws IllegalArgumentException
053     *             if either String input {@code null}
054     */
055    @Override
056    public Integer apply(final CharSequence left, final CharSequence right) {
057        // Quick return for invalid inputs
058        if (left == null || right == null) {
059            throw new IllegalArgumentException("Inputs must not be null");
060        }
061        return left.length() + right.length() - 2 * longestCommonSubsequence.apply(left, right);
062    }
063
064}