We help IT Professionals succeed at work.

How to find and return all the common substrings of a string pair

wsyy
wsyy asked
on
Hi,

I have googled a solution to find the longest common substring of a string pair. Now I want to find and return all the common substrings of a string pair. Does any one have a solution in Java handy?

By the way, I would like to have the longest common substring in the result set, just in case that the solution would remove it from the result set.

Thanks
Comment
Watch Question

Awarded 2011
Awarded 2011

Commented:
This is longest common subtsring from

http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Java

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;
}

Open in new window

Awarded 2011
Awarded 2011

Commented:
By the way there two more implemnattions in Java in the same linkk below
Awarded 2011
Awarded 2011

Commented:
Are you talking about substrings or subsequences ?
I guess, substrings are consecutive

Author

Commented:
I have founded the link, thanks.

I am talking about subsequences, with one condition that the length of each subsequence is more than 1.

Awarded 2011
Awarded 2011
Commented: