求字符串的最长公共子串

找两个字符串的最长公共子串,这个子串要求在原字符串中是连续的。而最长公共子序列不要求连续

代码如下:

 

package string;

import java.util.ArrayList;
import java.util.List;
/**
 * 字符串的最长公共子串问题
 * @author Administrator
 *
 */
public class LCString {
    /**
     * 求最长公共子串长度
     * @param s1
     * @param s2
     * @return
     */
    public int getMaxLen(String s1, String s2){
        if(s1 == null || s2 == null){
            return 0;
        }
        int m = s1.length();
        int n = s2.length();
        // a[i][j]表示以s1中以i-1结尾,s2中以j-1结尾的最长公共子串长度
        int[][] a = new int[m+1][n+1];
        int maxLen = 0;
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                if(s1.charAt(i-1) == s2.charAt(j-1)){
                    a[i][j] = a[i-1][j-1]+1;
                }else{
                    a[i][j] = 0;
                }
                maxLen = Math.max(maxLen, a[i][j]);
            }
        }
        return maxLen;
    }
    
    /**
     * 求最长公共子串
     * @param s1
     * @param s2
     * @return
     */
    public List<String> getMaxSubString(String s1, String s2){
        List<String> res = new ArrayList<String>();
        if(s1 == null || s2 == null){
            return res;
        }
        int m = s1.length();
        int n = s2.length();
        int maxLen = 0;
        // a[i][j]表示以s1中以i-1结尾,s2中以j-1结尾的最长公共子串的长度
        int[][] a = new int[m+1][n+1];
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                a[i][j] = s1.charAt(i-1) == s2.charAt(j-1) ? a[i-1][j-1]+1 : 0;
                if(a[i][j] == maxLen){
                    String s = s1.substring(i-a[i][j], i);
                    if(!res.contains(s)){
                        res.add(s);
                    }
                } else if(a[i][j] > maxLen){
                    res = new ArrayList<String>();
                    res.add(s1.substring(i-a[i][j], i));
                    maxLen = a[i][j];
                }
            }
        }
        return res;
    }
    
    public static void main(String[] args) {
        LCString m = new LCString();
//        String s1 = "bab";
//        String s2 = "caba";
        String s1 = "123456abcd567";
        String s2 = "234dddabc45678";
        System.out.println(m.getMaxLen(s1, s2));
        System.out.println(m.getMaxSubString(s1, s2));
    }

}

 

posted @ 2016-09-14 10:18  ~风轻云淡~  阅读(700)  评论(0编辑  收藏  举报