/**
* 根据传入的两个字符串判断相似度并转换格式返回带百分号的字符串
*
* @param str
* @param target
*/
public static String getSimilarityRatioString(String str, String target) {
// 获取相似度
float a = getSimilarityRatio(str, target);
// 转换为字符串
String result = String.valueOf(a);
// 截取整数部分
result = result.substring(0, result.lastIndexOf("."));
// 转换为数字
int num = Integer.valueOf(result);
return num + "%";
}
/**
* 计算两个字符串的相似度,返回小数
*
* @param str
* @param target
* @return
*/
public static float getSimilarityRatio(String str, String target) {
// 矩阵
int[][] d;
int n = str.length();
int m = target.length();
// 遍历str的
int i;
// 遍历target的
int j;
// str的
char ch1;
// target的
char ch2;
// 记录相同字符,在某个矩阵位置值的增量,不是0就是1
int temp;
if (n == 0 || m == 0) {
return 0;
}
d = new int[n + 1][m + 1];
// 初始化第一列
for (i = 0; i <= n; i++) {
d[i][0] = i;
}
// 初始化第一行
for (j = 0; j <= m; j++) {
d[0][j] = j;
}
// 遍历str
for (i = 1; i <= n; i++) {
ch1 = str.charAt(i - 1);
// 去匹配target
for (j = 1; j <= m; j++) {
ch2 = target.charAt(j - 1);
if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
temp = 0;
} else {
temp = 1;
}
// 左边+1,上边+1, 左上角+temp取最小
d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + temp);
}
}
return (1 - (float) d[n][m] / Math.max(str.length(), target.length())) * 100F;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交