java题目 HJ65 查找两个字符串a,b中的最长公共子串
描述
查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
注:子串的定义:将一个字符串删去前缀和后缀(也可以不删)形成的字符串。请和“子序列”的概念分开!
数据范围:字符串长度1\le length \le300 \1≤length≤300
进阶:时间复杂度:O(n^3)\O(n3) ,空间复杂度:O(n)\O(n)
输入描述:
输入两个字符串
输出描述:
返回重复出现的字符
示例1
输入:
abcdefghijklmnop abcsafjklmnopqrstuvw
输出:
jklmnop
1 import java.util.*; 2 public class Main{ 3 public static void main(String[] args) { 4 Scanner sc = new Scanner(System.in); 5 while (sc.hasNext()) { 6 String shortStr = sc.next(); 7 String longStr = sc.next(); 8 //保证第一个参数为较短串 9 if(shortStr.length()<longStr.length()){ 10 System.out.println(sunStr(shortStr,longStr)); 11 }else { 12 System.out.println(sunStr(longStr,shortStr)); 13 } 14 } 15 } 16 17 public static String sunStr(String shortStr, String longStr){ 18 //计算最长子串 19 String result; 20 if(longStr.contains(shortStr)) { 21 return result = shortStr; 22 } 23 int len = shortStr.length() -1; //从短字符串的 length-1开始遍历 24 for(int i =0; i<shortStr.length(); i++) { 25 if(i+ len <= shortStr.length()) { //子串末尾不能超出short长度 26 result = shortStr.substring(i, i+len); 27 if(longStr.contains(result)) 28 return result; 29 } else { 30 len--; 31 i = -1; 32 } 33 } 34 //所有长度遍历 35 return null; 36 } 37 }