java HJ75 公共子串計算
阿新 • • 發佈:2022-03-13
描述
給定兩個只包含小寫字母的字串,計算兩個字串的最大公共子串的長度。
注:子串的定義指一個字串刪掉其部分字首和字尾(也可以不刪)後形成的字串。資料範圍:字串長度:1\le s\le 150\1≤s≤150 進階:時間複雜度: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 }