题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

思路:在一位牛油那里得到启发,并做了相应精简。
1.由于当最长公共子串不唯一时,需要输出较短字符串的出现的第一个最长公共子串。因此需要先判断除最短字符串。
2.对最短字符串做双重for循环,若i与j之间的子串在较长字符串中存在,并且长度大于max。记录下当前的i与j。
3.循环结束,输出较短字符串在i与j之间的子串。

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str1=in.next();
            String str2=in.next();
            //找出较短子串
            if(str1.length()>str2.length()){
                String tmp=str2;
                str2=str1;
                str1=tmp;
            }
            int max=0;//记录最大公共子串长度
            int m=0;//记录最大公共子串的左边界
            int n=0;//记录最大公共子串的右边界
            for(int i=0;i<str1.length();i++){
                for(int j=i+1;j<=str1.length();j++){
                    if(str2.contains(str1.substring(i,j)) && j-i>max){
                        max=j-i;
                        m=i;n=j;
                    }
                }
            }
            System.out.println(str1.substring(m,n));
        }
    }
全部评论

相关推荐

点赞 2 评论
分享
牛客网
牛客企业服务