我需要找出一个字符串包含多少百分比或字符到另一个字符串中。 我已经尝试了Levenshtein Distance,但是该算法返回了为了使字符串相等需要更改多少字符。 有人可以帮忙吗? 我需要它在c#中,但那不是那么重要。
答案代码: public double LongestCommonSubsequence(string s1,string s2) { //如果任一字符串为空,则长度必须为0 if(String.IsNullOrEmpty(s1)|| String.IsNullOrEmpty(s2)) 返回0;
int[,] num = new int[s1.Length, s2.Length]; //2D array
char letter1;
char letter2;
//Actual algorithm
for (int i = 0; i < s1.Length; i++)
{
letter1 = s1[i];
for (int j = 0; j < s2.Length; j++)
{
letter2 = s2[j];
if (letter1 == letter2)
{
if ((i == 0) || (j == 0))
num[i, j] = 1;
else
num[i, j] = 1 + num[i - 1, j - 1];
}
else
{
if ((i == 0) && (j == 0))
num[i, j] = 0;
else if ((i == 0) && !(j == 0)) //First ith element
num[i, j] = Math.Max(0, num[i, j - 1]);
else if (!(i == 0) && (j == 0)) //First jth element
num[i, j] = Math.Max(num[i - 1, j], 0);
else // if (!(i == 0) && !(j == 0))
num[i, j] = Math.Max(num[i - 1, j], num[i, j - 1]);
}
}//end j
}//end i
return (s2.Length - (double)num[s1.Length - 1, s2.Length - 1]) / s1.Length * 100;
} //end LongestCommonSubsequence
答案 0 :(得分:2)
听起来你可能想要longest common subsequence这是diff算法的基础。不幸的是,这个问题是NP难的,这意味着没有有效的(多项式时间)解决方案。维基百科页面有一些建议。
答案 1 :(得分:0)
呃......你不能只使用那些需要改变的字符数吗?
(length(destination)-changed_character_count)/ length(source)
编辑:根据修订后的问题,将两个字符串视为集合,计算集合交集,并将该集合的大小和源字符串的百分比作为集合。