最大公共子串

来源:互联网 发布:js 数组方法 indexof 编辑:程序博客网 时间:2024/06/02 13:10

问题:找出“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));    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
cvhellohnmcvhellohnvhellohnmcvhellohvhellohnhellohnmcvhellovhellohhellohnellohnmcvhellvhellohellohellohnllohnmcvhelvhellhellos1、s2的最大子串hello
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19


从运行结果中可以很清楚的看出,短串temp是逐步缩短长度,然后去长串中进行查找的

原创粉丝点击