编辑距离,又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。
例如将kitten一字转成sitting:
- sitten (k→s)
- sittin (e→i)
- sitting (→g)
俄罗斯科学家Vladimir Levenshtein在1965年提出这个概念。
(以上概念介绍来自维基百科,“编辑距离”,http://zh.wikipedia.org/wiki/%E7%B7%A8%E8%BC%AF%E8%B7%9D%E9%9B%A2)
求最小编辑距离,即是从一个字符串转换成另一个所需要的最少的插入、删除、替换的操作次数。
常用的一个解法是动态规划。
具体的计算方法,请查阅相关文章,此不赘述。
空间复杂度为O(mn)的方法,是计算上面的矩阵时,保留所有的结果。
Java工具包Apache的StringUtils类(在包commons-lang中,最新为commons-lang3-3.3.2)中采用的则是仅保留上一行的结果。减少的空间,并且避免长字符串时的内容溢出。详细请查看该包的源代码org.apache.commons.lang3.StringUtils 中的StringUtils.getLevenshteinDistance(CharSequence s, CharSequence t);中。
// Misc
//-----------------------------------------------------------------------
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The previous implementation of the Levenshtein distance algorithm
* was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
* which can occur when my Java implementation is used with very large strings.<br>
* This implementation of the Levenshtein distance algorithm
* is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringU