题解 | #最长公共子串#注意多个起点(遍历其中一个字符串,嵌套遍历第二个动态查找)

最长公共子串

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

import java.util.*;
import java.lang.String;


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) {
        // write code here
        String res = "";

        //思路:遍历其中一个串 依次去尝试得到最长的串,比较保留较长的串
        for(int i =0;i<str1.length();i++){
            char cur = str1.charAt(i);
            for(int j = 0;j<str2.length();j++){
                if(str2.charAt(j)== cur){//注意可能有多个
                    String curStr = getMaxLength(str1,str2,i,j);
                    res = res.length() > curStr.length() ? res : curStr;
                }
            }
        }
        return res;
    }

    public String getMaxLength(String s1,String s2,int i,int j){

        String result = "";

        while(i <s1.length() && j < s2.length()){
            char next = s1.charAt(i);
            if(next == s2.charAt(j)){
                result += next;
                i ++;
                j ++;
            } else {
                return result;
            }
        }
        return result;
    }
}
全部评论

相关推荐

风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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