11077 最长公共子字符串

234 阅读2分钟

时间限制:1000MS 内存限制:65535K

题型: 编程题 语言: 无限制

Description 求两个输入序列的最长的公共子字符串的长度。子字符串中的所有字符在源字符串中必须相邻。

如字符串:21232523311324和字符串312123223445,他们的最长公共子字符串为21232,长度为5。

输入格式 两行,第一行为第一个字符串X,第二行为第二个字符串Y,字符串不含空格并以回车标示结束。X和Y的串长都不超过100000

输出格式 两行,第一行为最长的公共子字符串的长度,第二行输出一个最长的公共子字符串。

说明: (1)若最长的公共子字符串有多个,请输出在源字符串X中靠左的那个。 (2)若最长公共子字符串的长度为0,请输出空串(一个回车符)。

如输入:

21232523311324

152341231 由于523和123都是最长的公共子字符串,但123在源串X中更靠左,因此输出:

3

123

输入样例 21232523311324

312123223445

输出样例 5

21232

#include <stdio.h>
#include <string.h>
using namespace std;
char a[1000],b[1000]; //1000够了
int m[1000][1000];
int a_num,b_num;
int res=-1;
int mark;
void findL(){
    for(int i=0;i<a_num;i++){
        for(int j=0;j<b_num;j++){
            if(a[i]==b[j]){
                if(i==0||j==0) m[i][j]=1;
                else{
                    m[i][j] = m[i-1][j-1]+1;
            }
            }else{
            m[i][j]=0;
            }
        }
    }
    for(int i=a_num-1;i>=0;i--){   //输出在源字符串X中靠左的那个
        for(int j=0;j<b_num;j++){
            if(res<=m[i][j])    // 注意是小于等于
               {
                   res = m[i][j];
                   mark = i;
               }
        }
    }
}
int main()
{
    cin >> a >> b;
    a_num=strlen(a);b_num=strlen(b);
    findL();
    cout << res<< endl;
    for(int i=mark-res+1;i<mark+1;i++){
       cout << a[i];
    }
    return 0;
}

方法2:

public class Main {
    //生成dp数组
    public static int[][] getdp(char[] c1, char[] c2) {
        
        int len1 = c1.length;
        int len2 = c2.length;
        
        int[][] dp = new int[len1][len2];
        
        //第一行填充
        for(int j=0; j<len2; j++) {
            if(c1[0] == c2[j]) {
                dp[0][j] = 1;
            }
        }
        
        //第一列填充
        for(int i=0; i<len1; i++) {
            if(c1[i] == c2[0]) {
                dp[i][0] = 1;
            }
        }
        
        for(int i=1; i<len1; i++) {
            for(int j=1; j<len2; j++) {
                if(c1[i] == c2[j]) {
                    dp[i][j] = dp[i-1][j-1]+1;
                }
            }
        }
        
        return dp;
    }
    
    public static String lcs(String s1, String s2) {
        if(s1==null || s1.length()==0 || s2==null || s2.length()==0) {
            return null;
        }
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        
        int[][] dp = getdp(c1, c2);
        
        int row = dp.length;
        int col = dp[0].length;
        
        int end = 0;
        int max =0;
        for(int i=0; i<row; i++) {
            for(int j=0; j<col; j++) {
                if(dp[i][j]>=max) {
                    max = dp[i][j];
                    end = i;
                }
            }
        }
        
    return s1.substring(end-max+1,end+1);
    }
    
    public static void main(String[] args) {
        String s1 = "A1234B";
        String s2 = "CD1234";
        
        System.out.println(lcs(s1, s2));
    }
}
```