JAVA相似算法的运用
今天要处理问题是把一个产品的名字按照其内容对比文档转换出它的中文名。
但是这个文档感觉不全,产品种类有多又杂。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。如果像这样写的话
if(xxx.contains())
else if()
...
不知要写多久,错误率也高,后期也没法维护。
其中文档有产品的通配文件名称
我就考虑到了相似算法,直接比对产品通配名称,那个相似度高,就能决定产品中文名
下面直接上代码
/*** * 完全相似=1.0 * 完全不相似=0.0 */ public static float getSimilarityRatio(String str, String target) { return 1 - (float) compare(str, target) / Math.max(str.length(), target.length()); } private static int compare(String str, String target) { int d[][]; // 矩阵 int n = str.length(); int m = target.length(); int i; // 遍历str的 int j; // 遍历target的 char ch1; // str的 char ch2; // target的 int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1 if (n == 0) { return m; } if (m == 0) { return n; } 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; } for (i = 1; i <= n; i++) { // 遍历str ch1 = str.charAt(i - 1); // 去匹配target for (j = 1; j <= m; j++) { ch2 = target.charAt(j - 1); if (ch1 == ch2) { temp = 0; } else { temp = 1; } // 左边+1,上边+1, 左上角+temp取最小 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp); } } return d[n][m]; } private static int min(int one, int two, int three) { return (one = one < two ? one : two) < three ? one : three; }
转自:https://blog.csdn.net/JavaReact/article/details/82144732
更多精彩