Levenshtein Distance,判断字符串的相似性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | private int LevenshteinDistance( string s1, string s2, int maxValue) { if (s1 == null || s1.Length == 0) return maxValue; if (s2 == null || s2.Length == 0) return maxValue; if (s1.Trim() == s2.Trim()) return 0; // create two work vectors of integer distances int [] v0 = new int [s2.Length + 1]; int [] v1 = new int [s2.Length + 1]; int [] vtemp; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for ( int i = 0; i < v0.Length; i++) { v0[i] = i; } for ( int i = 0; i < s1.Length; i++) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1; // use formula to fill in the rest of the row for ( int j = 0; j < s2.Length; j++) { int cost = 1; if (s1.Substring(i, 1) == s2.Substring(j, 1)) { cost = 0; } v1[j + 1] = Math.Min( v1[j] + 1, // Cost of insertion Math.Min( v0[j + 1] + 1, // Cost of remove v0[j] + cost)); // Cost of substitution } // copy v1 (current row) to v0 (previous row) for next iteration //System.arraycopy(v1, 0, v0, 0, v0.length); // Flip references to current and previous row vtemp = v0; v0 = v1; v1 = vtemp; } return Math.Min(v0[s2.Length],maxValue); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
2016-08-29 数据库设计