此篇只是个整理,参考了如下链接:
http://www.linuxso.com/architecture/9008.html
最近在考虑如何求字符串相似度计算的问题,查了很多,有两种方式
1.向量
/**
* 计算字符串相似度
* @return
*/
public static double computeSimilarity(String str, String compareTo) {
char[] strChars = str.toCharArray();
char[] compareToChars = compareTo.toCharArray();
long vecProduct = 0;
long strProduct = 0;
long compareToProduct = 0;
double strCharsAbs = 0.0;
double compareToCharsAbs = 0.0;
double strSimilarity = 0.0;
int vecLen = 0;
if(str.length() <= compareTo.length()) {
vecLen = str.length();
} else {
vecLen = compareTo.length();
}
for(int i = 0; i < vecLen; i++) {
vecProduct += strChars[i] * compareToChars[i];
}
for(int i = 0; i < str.length(); i++) {
strProduct += strChars[i] * strChars[i];
}
strCharsAbs = Math.sqrt(strProduct);
for(int i = 0; i < compareTo.length(); i++) {
compareToProduct += compareToChars[i] * compareToChars[i];
}
compareToCharsAbs = Math.sqrt(compareToProduct);
strSimilarity = vecProduct / (strCharsAbs * compareToCharsAbs);
return strSimilarity;
}
这个算法我是按照向量夹角公式实现的,但是在测试的时候是存在很大问题的,
比如“abc“,”def“完全不相同的两个字符串相似度是99%,后来发现我是按照它们的asc码作为
它们的向量值的,所以才会出现这样的结果,希望哪位大虾可以帮忙改正
2.Levenshtein distance 算法
这个算法满足了我的要求,具体可以参考链接中的原文