/*
In information theory and computer science, the Damerau–Levenshtein distance
(named after Frederick J. Damerau and Vladimir I. Levenshtein) is a "distance"
(string metric) between two strings, i.e., finite sequence of symbols, given by
counting the minimum number of operations needed to transform one string into the other,
where an operation is defined as an insertion, deletion, or substitution of a single character,
or a transposition of two adjacent characters.
兩個字符序列的DL距離,就是從一個變換到另一個的最小操作次數。這個變換包括插入一個字符、洗掉一個字符、
替換一個字符、或互換兩個相鄰字符。
而所謂“編輯距離(edit distance,或叫Levenshtein distance)”,并不包含互換兩個相鄰字符。
還有計算字串相似度的函式 StringSimilarityRatio(Str1, Str2, IgnoreCase): Double;
回傳值在0到1之間,0表示不相似,1表示完全相似。
*/
float DamerauLevenshteinDistance(CString source, CString target)
{
float similarity=0;
int **H,m,n;
CString From, To;
int i,j;
if (source.IsEmpty())
{
if (target.IsEmpty())
{
similarity = 1;
return 0;
}
else
{
similarity = 0;
return (float)target.GetLength();
}
}
else if (target.IsEmpty())
{
similarity = 0;
return (float)source.GetLength();
}
//
From = source;
To = target;
// 初始化
m = From.GetLength();
n = To.GetLength();
//
H = new int* [m+1];
for(i=0;i <= m;i++)//not n
H[i]=new int[n+1];
for(i = 0; i <= m; i++)
H[i][0] = i;
for(j = 1; j <= n; j++)
H[0][j] = j;
// 迭代
for (i = 1; i <= m; i++)
{
char SI=From.GetAt(i-1);
for (j = 1; j <= n; j++)
{ // 洗掉 插入 替換
char DJ=To.GetAt(j-1);
if (SI == DJ)
{
H[i][ j] = H[i - 1][ j - 1];
}
else
{
H[i] [j] = min(H[i - 1][j - 1], min(H[i - 1][j], H[i][j - 1]))+ 1;
}
if (i > 1 && j > 1)
{
int ii = From.Mid (i - 2, i - 1).Find(DJ);
if (ii != -1)
{
int jj=To.Mid (j - 2, j - 1).Find(SI);
if (jj != -1)
{ //將源串i1到i-1內的字符洗掉,然后交換i1和i-1的字符,再加上目標串j1到j-1內的字符
H[i][ j] =min(H[i][ j], H[ii][ jj] + (i - ii - 2) + 1 + (j - jj - 2));
}
}
}
}
}
// 計算相似度
int MaxLength = max(m, n); // 兩字串的最大長度
similarity = float((MaxLength - H[m][n]))/ float(MaxLength);
//
for(i=0;i <= m; i++)// not n
{
// afxDump << *H[i] << "\r\n";//0->7
delete[] H[i];
}
眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......
值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......