    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. <em>Applied combinatorics on words</em>. New York: Cambridge U Press, 2005. <strong>12-13</strong></p>
    034 *
    035 * @since 1.0
    036 */
    037public class LongestCommonSubsequenceDistance implements EditDistance<Integer> {
    038
    039    /**
    040     * Creates a new instance.
    041     */
    042    public LongestCommonSubsequenceDistance() {
    043        // empty
    044    }
    045
    046    /**
    047     * Calculates an edit distance between two {@code CharSequence}'s {@code left} and
    048     * {@code right} as: {@code left.length() + right.length() - 2 * LCS(left, right)}, where
    049     * {@code LCS} is given in {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
    050     *
    051     * @param left first character sequence
    052     * @param right second character sequence
    053     * @return distance
    054     * @throws IllegalArgumentException
    055     *             if either String input {@code null}
    056     */
    057    @Override
    058    public Integer apply(final CharSequence left, final CharSequence right) {
    059        // Quick return for invalid inputs
    060        if (left == null || right == null) {
    061            throw new IllegalArgumentException("Inputs must not be null");
    062        }
    063        return left.length() + right.length() - 2 * LongestCommonSubsequence.INSTANCE.apply(left, right);
    064    }
    065
    066}