日期:2014-05-20 浏览次数:20668 次
/** * 程序目的: * 请编程求解两个字符串中的最大子串,例如abcdefg和nbcdyu中的最大子串为bcd。 * */ public class $3_MaxSubString { public static void main(String[] args) { String longStr = "sadfasdf"; String shortStr ="gasdsadf"; System.out.println(maxSubString(longStr,shortStr)); } public static String maxSubString(String longStr,String shortStr){ //保证前面的字符串长度大于后面的字符串长度 if(longStr.length()<shortStr.length()){ String temp = longStr; longStr = shortStr; shortStr = temp; } String maxsub; String subLong; for(int i=shortStr.length();i>0;i--){ //定义小字符串取的长度 for(int j=0;j<=shortStr.length()-i;j++){ //定义小串取的位置 maxsub = shortStr.substring(j,i+j); for(int k=0;k<=longStr.length()-maxsub.length();k++){ subLong = longStr.substring(k, maxsub.length()+k); if(maxsub.equals(subLong))return maxsub; } } } return null; } }
public final class MaxSubString { public static void main(String[] args) { MaxSubString maxSubString = new MaxSubString(); System.out.println("[" + maxSubString.maxSubString("abcdefg", "nbcdyu") + "]"); } private String maxSubStr; public String maxSubString(final String strA, final String strB) { String strAA = strA; String strBB = strB; if (strA.length() < strB.length()) { strAA = strB; strBB = strA; } this.maxSubStr = ""; String result = null; String subStrB = null; int loops = strBB.length(); for (int i = 0; i < loops; i++) { subStrB = strBB.substring(i); for (int j = subStrB.length(); j > 0; j--) { result = subStrB.substring(0, j); if (strAA.contains(result)) { if (this.maxSubStr.length() < result.length()) { this.maxSubStr = result; } } } } return this.maxSubStr; } }