將開發(fā)過程中較好的一些代碼段備份一下,下面的代碼是關(guān)于C#通過編輯距離計(jì)算兩個(gè)字符串的相似度的代碼,應(yīng)該能對(duì)碼農(nóng)們有些幫助。
成都創(chuàng)新互聯(lián)公司長(zhǎng)期為近1000家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為南川企業(yè)提供專業(yè)的成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站,南川網(wǎng)站改版等技術(shù)服務(wù)。擁有10余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Levenshtein
{
public delegate void AnalyzerCompletedHander(double sim);
public class LevenshteinDistance:IDisposable
{
private string str1;
private string str2;
private int[,] index;
int k;
Task task;
public event AnalyzerCompletedHander AnalyzerCompleted;
public string Str1
{
get { return str1; }
set
{
str1 = Format(value);
index = new int[str1.Length, str2.Length];
}
}
public string Str2
{
get { return str2; }
set
{
str2 = Format(value);
index = new int[str1.Length, str2.Length];
}
}
public int TotalTimes
{
}
public bool IsCompleted
{
get { return task.IsCompleted; }
}
public LevenshteinDistance(string str1, string str2)
{
this.str1 = Format(str1);
this.str2 = Format(str2);
index = new int[str1.Length, str2.Length];
}
public LevenshteinDistance()
{
}
public void Start()
{
task = new Task(Analyzer);
task.Start();
task.ContinueWith(o => Completed(o.Result));
}
public double StartAyns()
{
task = new Task(Analyzer);
task.Start();
task.Wait();
return task.Result;
}
private void Completed(double s)
{
if (AnalyzerCompleted != null)
{
AnalyzerCompleted(s);
}
}
private double Analyzer()
{
if (str1.Length == 0 || str2.Length == 0)
return 0;
for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
k = str1[i] == str2[j] ? 0 : 1;
if (i == 0&&j==0)
{
continue;
}
else if (i == 0)
{
index[i, j] = k + index[i, j - 1];
continue;
}
else if (j == 0)
{
index[i, j] = k + index[i - 1, j];
continue;
}
int temp = Min(index[i, j - 1],
index[i - 1, j],
index[i - 1, j - 1]);
index[i, j] = temp + k;
}
}
float similarty = 1 - (float)index[str1.Length - 1, str2.Length - 1]
/ (str1.Length > str2.Length ? str1.Length : str2.Length);
return similarty;
}
private string Format(string str)
{
str = Regex.Replace(str, @"[^a-zA-Z0-9u4e00-u9fa5s]", "");
return str;
}
private int Min(int a, int b, int c)
{
int temp = a < b ? a : b;
temp = temp < c ? temp : c;
return temp;
}
public void Dispose()
{
task.Dispose();
}
}
}
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國(guó)云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開啟,新人活動(dòng)云服務(wù)器買多久送多久。