我需要找出一個字符串包含在另一個字符串中的百分比或字符數。 我試過了Levenshtein距離,但是那個算法返回需要多少字符來改變字符串是否相等。 有人可以幫忙嗎? 我需要它在C#但這並不重要。找出一個字符串在另一個字符串中包含多少百分比
答案代碼: 公共雙LongestCommonSubsequence(串S1,字符串s2) { //如果任一字符串是空的,長度必須爲0 如果(String.IsNullOrEmpty(S1)|| String.IsNullOrEmpty( s2)) return 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
字符的順序是否重要? – 2010-06-18 23:13:39
你缺少的例子。這個問題非常模糊。 – Anurag 2010-06-18 23:23:00
我不好寫的例子,確定他們是:) 例如: string a = John Malkovich; string b = Joahn Mulkovich; 這些字符串之間的差異是2個字符,或者它們是相同的84.6%。例如, 2: string a = John Malkovich; string b = Jonh Malkovich; 他們是一樣的84.6% 希望我會有所幫助。 – Pece 2010-06-18 23:32:51