问题:找出“abcwerthelloyuiodef”和“cvhellohnm”的最长公共子串 该题的关键不在于匹配,而在于匹配之前如何截短子串,提高查找效率,
思路: step1. 先区分哪个是长串,哪个是短串 step2. 用短串直接去长串中匹配,找到则返回该短串,否则进入step3 step3. 将短串长度进行削减,将削减后的短串作为新的短串,接着执行step2
图示: 代码实现:
package string; public class MaxStringDemo { /** * 1.确定长串和短串 * 2.直接用短串去长串中查找,如果查找到则返回,没有则进入第3步 * 3.将短串长度减一,取子串 * 4.取同长度短串的下一种情况 */ public static String getMaxSubString(String s1, String s2){ String max = "",min=""; //确定长串和短串 max = (s1.length() > s2.length())?s1:s2; min = (s1==max)?s2:s1; for(int x=0; x<min.length(); x++){ for(int y=0,z=min.length()-x;z!=min.length()+1; y++,z++){ String temp = min.substring(y,z); System.out.println(temp);//让运行时打印出匹配情况 if(max.contains(temp)){//另一种写法:if(s1.indexOf(temp)!=-1) return temp; } } } return null; } /** * @param args */ public static void main(String[] args) { String s1 = "abcwerthelloyuiodef"; String s2 = "cvhellohnm"; System.out.println("s1、s2的最大子串"+getMaxSubString(s1,s2)); } } cvhellohnm cvhellohn vhellohnm cvhelloh vhellohn hellohnm cvhello vhelloh hellohn ellohnm cvhell vhello helloh ellohn llohnm cvhel vhell hello s1、s2的最大子串hello从运行结果中可以很清楚的看出,短串temp是逐步缩短长度,然后去长串中进行查找的
