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