Source code
Description: source: package: org.apache.commons.text.similarity, class: LongestCommonSubsequenceDistance

    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     * Calculates an edit distance between two {@code CharSequence}'s {@code left} and
    041     * {@code right} as: {@code left.length() + right.length() - 2 * LCS(left, right)}, where
    042     * {@code LCS} is given in {@link LongestCommonSubsequence#apply(CharSequence, CharSequence)}.
    043     *
    044     * @param left first character sequence
    045     * @param right second character sequence
    046     * @return distance
    047     * @throws IllegalArgumentException
    048     *             if either String input {@code null}
    049     */
    050    @Override
    051    public Integer apply(final CharSequence left, final CharSequence right) {
    052        // Quick return for invalid inputs
    053        if (left == null || right == null) {
    054            throw new IllegalArgumentException("Inputs must not be null");
    055        }
    056        return left.length() + right.length() - 2 * LongestCommonSubsequence.INSTANCE.apply(left, right);
    057    }
    058
    059}