Class LevenshteinDistance
java.lang.Object
cloud.opencode.base.string.similarity.LevenshteinDistance
Levenshtein Distance - Calculates edit distance between strings.
编辑距离 - 计算字符串之间的编辑距离。
Features | 主要功能:
- Edit distance calculation - 编辑距离计算
- Similarity ratio calculation - 相似度比率计算
- O(n*m) time, O(m) space optimized - O(n*m)时间,O(m)空间优化
Usage Examples | 使用示例:
int distance = LevenshteinDistance.calculate("kitten", "sitting"); // 3
double similarity = LevenshteinDistance.similarity("hello", "hallo"); // 0.8
Security | 安全性:
- Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具类)
- Null-safe: No (throws IllegalArgumentException for null) - 空值安全: 否
- Since:
- JDK 25, opencode-base-string V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic intboundedDistance(String s1, String s2, int threshold) Bounded Levenshtein distance with early termination.static intstatic doublesimilarity(String s1, String s2)
-
Method Details
-
calculate
-
boundedDistance
Bounded Levenshtein distance with early termination. 带阈值的有界Levenshtein距离,提前终止。Returns the edit distance if
<= threshold, otherwise-1. Uses a banded DP algorithm that only computes a diagonal strip of width2*threshold+1, achieving O(min(m,n)*threshold) time.如果编辑距离
<= threshold则返回距离,否则返回-1。 使用带状DP算法,只计算对角线附近2*threshold+1宽度的区域, 时间复杂度为 O(min(m,n)*threshold)。Examples | 示例:
boundedDistance("kitten", "sitting", 3) = 3 boundedDistance("kitten", "sitting", 2) = -1 boundedDistance("abc", "abc", 0) = 0Performance | 性能:
Time: O(min(m,n) * threshold), Space: O(min(m,n))
- Parameters:
s1- the first string | 第一个字符串s2- the second string | 第二个字符串threshold- the maximum acceptable distance | 最大可接受距离- Returns:
- the edit distance if
<= threshold, otherwise-1| 如果编辑距离<= threshold则返回距离,否则返回-1 - Throws:
IllegalArgumentException- if either string is null or threshold is negative | 如果字符串为null或阈值为负数
-
similarity
-