前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最长公共连续子串

最长公共连续子串

作者头像
AI那点小事
发布2020-04-20 16:26:53
5680
发布2020-04-20 16:26:53
举报
文章被收录于专栏:AI那点小事

牛牛有两个字符串(可能包含空格),牛牛想找出其中最长的公共连续子串,希望你能帮助他,并输出其长度。 输入描述: 输入为两行字符串(可能包含空格),长度均小于等于50.

输出描述: 输出为一个整数,表示最长公共连续子串的长度。

输入例子: abcde abgde

输出例子: 2


PS:这道题不得不说真的很坑,先不说空格也算成字符,连最长公共连续子串这个概念也和刷传统相关题用的概念也一样。


代码如下:

代码语言:javascript
复制
import java.util.Scanner;

/**
 * @author Administrator
 *
 */
public class Main {
    static String str1;
    static String str2;
    static int[][] dp;
    static int Max;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        str1 = in.nextLine();
        str2 = in.nextLine();
        int len1 = str1.length();
        int len2 = str2.length();
        if ( len1 < 1 || len2 < 1){
            System.out.print(0);
        }

        dp = new int[str1.length()+1][str2.length()+1];
        char[] ch1 = str1.toCharArray();
        char[] ch2 = str2.toCharArray();

        for ( int i = 0 ; i < len1 ; i++){
            if ( ch1[i] == ch2[0]){
                dp[i][0] = 1;
            }
        }

        for ( int i = 0 ; i < len2 ; i++){
            if ( ch2[i] == ch1[0]){
                dp[0][i] = 1;
            }
        }

        Max = dp[0][0];
        for ( int i = 1 ; i < len1 ; i++){
            for ( int j = 1 ; j < len2 ; j++){
                if ( ch1[i] == ch2[j]){
                    dp[i][j] = dp[i-1][j-1]+1;
                }
                if ( dp[i][j] > Max){
                    Max = dp[i][j];
                }
            }
        }


        System.out.print(Max);
        in.close();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档