    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 *      https://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 {@code right} as:
    048     * {@code left.length() + right.length() - 2 * LCS(left, right)}, where {@code LCS} is given in
    049     * {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
    050     *
    051     * @param left  first character sequence.
    052     * @param right second character sequence.
    053     * @return distance.
    054     * @throws IllegalArgumentException if either String input {@code null}.
    055     */
    056    @Override
    057    public Integer apply(final CharSequence left, final CharSequence right) {
    058        // Quick return for invalid inputs
    059        if (left == null || right == null) {
    060            throw new IllegalArgumentException("Inputs must not be null");
    061        }
    062        return left.length() + right.length() - 2 * LongestCommonSubsequence.INSTANCE.apply(left, right);
    063    }
    064
    065}