14 .net c# vb.net visual-studio-2012
我在找到.net的最接近匹配字符串的实现时遇到问题
我想匹配一个字符串列表,例如:
输入字符串:"PublicznaSzkołaPodstawowaim.BolesławaChrobregowWąsoszu"
字符串列表:
PublicznaSzkołaPodstawowaim.B. ChrobregowWąsoszu
SzkołaPodstawowaSpecjalna
SzkołaPodstawowaim.Henryka SienkiewiczawWąsoszu
SzkołaPodstawowaim.Romualda TrauguttawWąsoszuGórnym
这显然需要与"PublicznaSzkołaPodstawowaim.B. ChrobregowWąsoszu"相匹配.
什么算法可用于.net?
das*_*ght 18
.NET不提供任何开箱即用的东西 - 您需要自己实现编辑距离算法.例如,您可以使用Levenshtein Distance,如下所示:
// This code is an implementation of the pseudocode from the Wikipedia,
// showing a naive implementation.
// You should research an algorithm with better space complexity.
public static int LevenshteinDistance(string s, string t) {
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
for (int i = 0; i <= n; d[i, 0] = i++)
;
for (int j = 0; j <= m; d[0, j] = j++)
;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
return d[n, m];
}
Run Code Online (Sandbox Code Playgroud)
调用LevenshteinDistance(targetString, possible[i])每个i,然后选择字符串possible[i]为其LevenshteinDistance返回最小值.
pap*_*zzo 16
编辑距离是通过计算将一个字符串转换为另一个字符串所需的最小操作数量来量化两个字符串(例如,字)彼此不相似的方式.
非正式地,两个单词之间的Levenshtein距离是将一个单词更改为另一个单词所需的单字符编辑(即插入,删除或替换)的最小数量.
using System;
/// <summary>
/// Contains approximate string matching
/// </summary>
static class LevenshteinDistance
{
/// <summary>
/// Compute the distance between two strings.
/// </summary>
public static int Compute(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
}
class Program
{
static void Main()
{
Console.WriteLine(LevenshteinDistance.Compute("aunt", "ant"));
Console.WriteLine(LevenshteinDistance.Compute("Sam", "Samantha"));
Console.WriteLine(LevenshteinDistance.Compute("flomax", "volmax"));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13901 次 |
| 最近记录: |