package stringTest; public class StringDemo4 { public static void main(String[] args) { String str1 = "Ilikejavaverymuch"; String str2 = "java is useful"; StringDemo4 sd4 = new StringDemo4(); sd4.sop(sd4.getMaxSubString1(str1, str2)); } /** * 求两个字符串的最大相同子串,思路: * 1、将短的字符串,按照长度递减的方式获取子串(核心) * 2、将每个获取的子串,判断是否在长的字符串中存在 * */ String getMaxSubString1(String str1, String str2) { String maxStr ="", minStr = ""; maxStr = str1.length() > str2.length() ? str1:str2; minStr = (maxStr == str1) ? str2:str1; for(int i = 0; i < minStr.length(); i++){ for(int start = 0, end = minStr.length()-i; end <= minStr.length(); start++, end++){ if (maxStr.contains(minStr.substring(start, end))){ return minStr.substring(start, end); } } } return ""; } //打印字符串 void sop(String str){ System.out.println("str = " + str + ""); } }
打印结果:
str = java
时间: 2024-11-08 19:49:07