Simple string Similarity Calculation

Source: Internet
Author: User

Calculates the levenshtein distance and returns a ratio to a long string.

Code

 /// <Summary>
/// Levenshtein distance
/// </Summary>
Static class stringext
{
/// <Summary>
/// Calculate the difference distance between two strings
/// </Summary>
/// <Param name = "Source"> source string </param>
/// <Param name = "target"> Target string </param>
/// <Returns> string gap </returns>
Public static int calcdistance (this string source, string target)
{
Int n = source. length;
Int M = target. length;
If (M = 0) return N;
If (n = 0) return m;
VaR matrix = new int [n + 1, m + 1];
For (INT I = 1; I <= N; I ++)
{
Matrix [I, 0] = I;
}
For (INT I = 1; I <= m; I ++)
{
Matrix [0, I] = I;
}

For (INT I = 1; I <= N; I ++)
{
VaR Si = source [I-1];
For (Int J = 1; j <= m; j ++)
{
VaR TJ = target [J-1];

Int cost;
If (SI = TJ)
Cost = 0;
Else
Cost = 1;

Int above = matrix [I-1, J] + 1;
Int left = matrix [I, j-1] + 1;
Int diag = matrix [I-1, J-1] + cost;
Matrix [I, j] = math. Min (above, math. Min (left, DIAG ));
}
}
Return matrix [n, m];
}

/// <Summary>
/// Calculate the similarity between two strings
/// </Summary>
/// <Param name = "Source"> source string </param>
/// <Param name = "target"> Target string </param>
/// <Returns> similarity </returns>
Public static double calcsimilarity (this string source, string target)
{
Int n = source. length;
Int M = target. length;
If (n = 0 | M = 0)
Return 0;
Int distance = source. calcdistance (target );
Int max = math. Max (n, m );
Return 1.0 * (max-distance)/max;
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.