zoukankan      html  css  js  c++  java
  • 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是逐步缩短长度,然后去长串中进行查找的

  • 相关阅读:
    使用docker部署zabbix
    如何用好 IDEA ,Java 撸码效率至少提升 5 倍?
    getpass模块
    linux下利用nohup后台运行jar文件包程序
    Spring Cloud 与 Dubbo 区别
    git 打标签并推送tag到托管服务器
    git-stash用法小结
    git推送本地分支到远程分支
    Git dev分支合并到master分支完美实战
    IntelliJ远程调试教程
  • 原文地址:https://www.cnblogs.com/shiguangmanbu2016/p/5932810.html
Copyright © 2011-2022 走看看