java面试题11--String--最大公共子串
2016-08-16 18:22
218 查看
问题:找出“abcwerthelloyuiodef”和“cvhellohnm”的最长公共子串
该题的关键不在于匹配,而在于匹配之前如何截短子串,提高查找效率,
思路:
step1. 先区分哪个是长串,哪个是短串
step2. 用短串直接去长串中匹配,找到则返回该短串,否则进入step3
step3. 将短串长度进行削减,将削减后的短串作为新的短串,接着执行step2
图示:
代码实现:
从运行结果中可以很清楚的看出,短串temp是逐步缩短长度,然后去长串中进行查找的
该题的关键不在于匹配,而在于匹配之前如何截短子串,提高查找效率,
思路:
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是逐步缩短长度,然后去长串中进行查找的
相关文章推荐
- java实现字符串匹配问题之求两个字符串的最大公共子串
- 关于 java中 求两个字符串中最大的公共子串之引发对return的用法探讨
- 【java编程】String之两个字符串获取最大子串
- 蓝桥杯第八届省赛JAVA真题----最大公共子串
- 2017第八届蓝桥杯 06 最大公共子串(java)
- 找出两个字符串中最大的公共子串(java实现)
- 蓝桥杯java第八届B组:最大公共子串
- java实现字符串匹配求两个字符串的最大公共子串
- “最长上升子序列,最大连续子序列和,最长公共子串”的Java实现
- 蓝桥杯java第八届第六题--最大公共子串
- 最大公共子串LCS(Java实现)
- 2017第八届蓝桥杯省赛Java A组--最大公共子串
- 第八届蓝桥杯【Java B组】最大公共子串
- java版求字符串的最大公共子串
- 面试题之求两个字符串的最大公共子串
- java实现字符串匹配问题之求两个字符串的最大公共子串
- “最长上升子序列,最大连续子序列和,最长公共子串”的Java实现
- Java String 字符串中的最大相同子串实现
- JAVA面试题解惑系列(六)——字符串(String)杂谈