Levenshtein 算法小记


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Levenshtein { public class SimilarityCompare { public int GetDistance(char[] src,char[] target) { //第一步,创建一个矩阵,列数为 src 长度+1,行数为 target 长度t+1 int[,] d;//矩阵 if (src.Length == 0) { return target.Length; } if (target.Length == 0) { return src.Length; } d = new int[src.Length + 1, target.Length + 1]; //第一步结束 //第二步,初始化矩阵 for (int x = 0; x <= src.Length; x++) { d[x, 0] = x;//设置第一行的初始值 } for (int y = 0; y <= target.Length; y++) { d[0, y] = y;//设置第一列的初始值 } //第二步结束 //第三步,计算距离 int cost=0; int above = 0; int left = 0; int diag = 0; for (int x = 1; x <= src.Length; x++) { for (int y = 1; y <= target.Length; y++) { if (src[x - 1] != target[y - 1]) { cost = 1; } else { cost = 0; } above = d[x, y - 1] + 1; left = d[x - 1, y] + 1; diag = d[x - 1, y - 1] + cost; d[x, y] = Math.Min(Math.Min(above, left), diag); } } //第三步结束 return d[src.Length, target.Length]; } } }

 

你可能感兴趣的:(算法,Class)