用于n个字符串的最长公共子字符串的Java实现

use*_*340 4 java longest-prefix suffix-array longest-substring

我需要找到n个字符串中最长的公共子字符串,并在我的项目中使用结果.

java中是否有现有的实现/库已经这样做了?

感谢您提前回复.

ded*_*dek 6

什么并发树

它是Maven Central中的一个小型(~100 KB)库.该算法使用RadixSuffix Trees的组合.众所周知,它具有线性时间复杂度(维基百科).

public static String getLongestCommonSubstring(Collection<String> strings) {
    LCSubstringSolver solver = new LCSubstringSolver(new DefaultCharSequenceNodeFactory());
    for (String s: strings) {
        solver.add(s);
    }
    return solver.getLongestCommonSubstring().toString();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我们可以使用下面的代码来识别n个字符串中最长的公共子字符串

public static String identifyCommonSubStrOfNStr(String [] strArr){

    String commonStr="";
    String smallStr ="";        

    //identify smallest String      
    for (String s :strArr) {
        if(smallStr.length()< s.length()){
            smallStr=s;
        }
    }

    String tempCom="";
    char [] smallStrChars=smallStr.toCharArray();               
    for (char c: smallStrChars){
        tempCom+= c;

        for (String s :strArr){
            if(!s.contains(tempCom)){
                tempCom=c;
                for (String s :strAarr){
                    if(!s.contains(tempCom)){
                        tempCom="";
                        break;
                    }
                }
                break;
            }               
        }

        if(tempCom!="" && tempCom.length()>commonStr.length()){
            commonStr=tempCom;  
        }                       
    }   

    return commonStr;
}
Run Code Online (Sandbox Code Playgroud)


dav*_*rld 0

页面几乎以多种语言提供了您想要的内容。

public static int longestSubstr(String first, String second) {
    if (first == null || second == null || first.length() == 0 || second.length() == 0) {
        return 0;
    }

    int maxLen = 0;
    int fl = first.length();
    int sl = second.length();
    int[][] table = new int[fl][sl];

    for (int i = 0; i < fl; i++) {
        for (int j = 0; j < sl; j++) {
            if (first.charAt(i) == second.charAt(j)) {
                if (i == 0 || j == 0) {
                    table[i][j] = 1;
                }
                else {
                    table[i][j] = table[i - 1][j - 1] + 1;
                }
                if (table[i][j] > maxLen) {
                    maxLen = table[i][j];
                }
            }
        }
    }
    return maxLen;
}
Run Code Online (Sandbox Code Playgroud)