java面试题11--String--最大公共子串


问题:找出“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是逐步缩短长度,然后去长串中进行查找的

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值