java HJ75 公共子串计算

描述

给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。

注:子串的定义指一个字符串删掉其部分前缀和后缀(也可以不删)后形成的字符串。
数据范围:字符串长度:1\le s\le 150\1s150 
进阶:时间复杂度:O(n^3)\O(n3) ,空间复杂度:O(n)\O(n) 

输入描述:

输入两个只包含小写字母的字符串

输出描述:

输出一个整数,代表最大公共子串的长度

示例1

输入:
asdfas
werasdfaswer
输出:
6

 

 

 1 import java.util.*;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         while(sc.hasNext()) {
 7             String s1 = sc.next();
 8             String s2 = sc.next();
 9             if(s1.length() < s2.length()) {
10                 System.out.println(calc(s1, s2));
11             }else {
12                 System.out.println(calc(s2, s1));
13             }
14         }
15     }
16     
17     public static int calc(String shortStr, String longStr) {
18         int count=0;
19 
20         
21         if(longStr.contains(shortStr)) {
22             count = shortStr.length();
23             return count;
24         }
25         int len = shortStr.length()-1;
26         while(len > 0) {
27             for(int i=0; i<shortStr.length(); i++) {  //对整个短字符串进行比遍历
28                 if(i+len <= shortStr.length()) {  //有边界不能超出短字符串
29                     if(longStr.contains(shortStr.substring(i,i+len))){
30                         count = shortStr.substring(i,i+len).length();
31                         return count;
32                     }
33                 }
34             }
35             len--;
36         }
37         return count;
38     }
39 }

 

posted @ 2022-03-13 18:27  海漠  阅读(163)  评论(0编辑  收藏  举报