计算两个字符串的编辑距离,判断相似度,常用于搜索建议、拼写纠错。
public class StringSimilarity { // 计算Levenshtein编辑距离 public static int CalculateLevenshteinDistance(string s1, string s2) { int[,] dp = new int[s1.Length + 1, s2.Length + 1]; // 初始化边界 for (int i = 0; i <= s1.Length; i++) dp[i, 0] = i; for (int j = 0; j <= s2.Length; j++) dp[0, j] = j; // 动态规划计算 for (int i = 1; i <= s1.Length; i++) { for (int j = 1; j <= s2.Length; j++) { int cost = s1[i - 1] == s2[j - 1] ? 0 : 1; dp[i, j] = Math.Min(Math.Min(dp[i - 1, j] + 1, dp[i, j - 1] + 1), dp[i - 1, j - 1] + cost); } } return dp[s1.Length, s2.Length]; } // 计算相似度(0-100%) public static double CalculateSimilarity(string s1, string s2) { if (string.IsNullOrEmpty(s1) && string.IsNullOrEmpty(s2)) return 100; if (string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2)) return 0; int distance = CalculateLevenshteinDistance(s1, s2); int maxLength = Math.Max(s1.Length, s2.Length); return (1 - (double)distance / maxLength) * 100; } // 调用示例 public static void TestSimilarity() { string s1 = "C#编程教程"; string s2 = "C#程序设计"; double similarity = CalculateSimilarity(s1, s2); Console.WriteLine($"相似度: {similarity:F2}%"); } }