题解 | #最长公共子串#

最长公共子串

http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac

import java.util.*;


public class Solution {
    /**
     * longest common substring
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String str1, String str2) {
        int start = 0;
        int end = 1; //初始条件:subString(0, 1),左闭右开,即只取第一个第0个字符
        String result = "";
        while(end <= str2.length()){ //subString左闭右开,所以可以取到等于
            String subStr = str2.substring(start, end);
            if(str1.contains(subStr)){
                result = subStr; // str1包含str2的该子串,例如:ab,继续右移看是否继续包含abc,所以end右移
            }else{
                start++; //str1不包含str2的该子串,例如:13,不必再找以13开头的子串了,因为不包含13,肯定也不包含134,所以start右移;因为需要找最长子串,start右移后,end也需要右移,保证长度不会缩短
            }
            end++; //上述两种情况,均需要end右移
        }
        return result;
    }
}
全部评论
这么多看下来 你这个最好理解
点赞 回复 分享
发布于 2022-04-12 13:42

相关推荐

今天 18:43
门头沟学院 Java
是暑期都招满了吗
投递腾讯等公司7个岗位
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
13
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务