存储最长字串的信息类:(由于我的需求不需要获取具体字串所以后面不会获取到,仅仅定义而已)
public class CommonResult { private String commonStr; private int commonCount; private int length; public CommonResult() { } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getCommonStr() { return commonStr; } public void setCommonStr(String commonStr) { this.commonStr = commonStr; } public int getCommonCount() { return commonCount; } public void setCommonCount(int commonCount) { this.commonCount = commonCount; } }关键算法:
//最长连续公共子串 public CommonResult maxUtilStr(String str1, String str2) { CommonResult commonResult = new CommonResult(); //把字符串转成字符数组 char[] arr1 = str1.toCharArray(); char[] arr2 = str2.toCharArray(); // 把两个字符串分别以行和列组成一个二维矩阵 int[][] temp = new int[arr1.length][arr2.length]; // 存储最长公共子串长度 int length = 0; //start表明最长公共子串的起始点,end表明最长公共子串的终止点 int end = 0; int start = 0; 初始化二维矩阵中的第一行 for (int i = 0; i < arr2.length; i++) { temp[0][i] = (arr1[0] == arr2[i]) ? 1 : 0; } //初始化二维矩阵中的第一列 for (int j = 0; j < arr1.length; j++) { temp[j][0] = (arr2[0] == arr1[j]) ? 1 : 0; } //嵌套for循环:比较二维矩阵中每个点对应行列字符中否相等,相等的话值设置为1,否则设置为0 //构建目标矩阵过程 for (int i = 1; i < arr1.length; i++) { for (int j = 1; j < arr2.length; j++) { if (arr1[i] == arr2[j]) { temp[i][j] = temp[i - 1][j - 1] + 1; if (temp[i][j] > length) { length = temp[i][j]; end = j; } } else { temp[i][j] = 0; } } } int arr_length = (arr1.length>arr2.length?arr1.length:arr2.length) + 1; int[] end_A=new int[arr_length]; //记录LCS在字符串A中结束的位置 int num_max_length = 0; //记录LCS的个数 boolean flag=true; //统计最长连续公共子串出现的个数 for(int i=0;i<arr1.length;i++){ for(int j=0;j<arr2.length;j++){ if(temp[i][j] == length){ num_max_length++; } } } //最长连续公共子串的个数 commonResult.setCommonCount(num_max_length); commonResult.setLength(length); return commonResult; }具体使用获取的数据进行需求处理:
CommonResult commonResult=new CommonResult(); for (Blog bb:blogList ) { //若是新增的帖子,则检查所有已有帖子标题,否则除了自身外的所有帖子都检测 if(blog.getId()==null || blog.getId()!=bb.getId()) commonResult=maxUtilStr(blog.getTitle(),bb.getTitle()); if(commonResult.getCommonCount()*commonResult.getLength()*1.0/blog.getTitle().length()>=0.8){ blog.setRr(1); break; } }