日期:2014-05-20  浏览次数:20668 次

[求助]帮忙测试,这个程序还有什么问题吗?
总觉得很麻烦!这样写有问题吗?还有更好的写法吗?
Java code

/**
 * 程序目的:
 * 请编程求解两个字符串中的最大子串,例如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;
    }
}



------解决方案--------------------
Java code
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;
    }
}