题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
       String stra = in.nextLine();
       String strb = in.nextLine();

     
       int a = stra.length();
       int b = strb.length();

       int maxLenth = 0;
       int endIndex =0;

      
       String result="";

       String orderA="";
       String orderB="";

       if(a>b){
            orderA = strb;
            orderB = stra;
       }else{
            orderA = stra;
            orderB = strb;
       }
    int[][] dp = new int[orderA.length()+1][orderB.length()+1];
       
       for(int i=1;i<=orderA.length();i++ ){
           for(int k=1;k<=orderB.length();k++){
              if(orderA.charAt(i-1)==orderB.charAt(k-1))
              {  dp[i][k] = dp[i-1][k-1]+1;//相同数目加1
                 if(dp[i][k]>maxLenth){
                    maxLenth = dp[i][k];//确定最长的长度
                    endIndex = i-1;//最后匹配终止的位置
                 }

              }

           }
       }
       
       outloop:
       for(int i=1;i<=orderA.length();i++){
          for(int k=0;k<=orderB.length();k++){
            if(dp[i][k]==maxLenth){
                endIndex=i-1;
                break outloop;
            }

          }
       }

  
        result = orderA.substring(endIndex-maxLenth+1,endIndex+1);
       
       if(maxLenth == 0)
       System.out.println("");
       else
       System.out.println(result);
    


    }
}

全部评论

相关推荐

10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
皮格吉:不,有的厂子面试无手撕,可以试试。都是一边学一边面。哪有真正准备好的时候,别放弃
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务