题解 | #最长公共子串#

最长公共子串

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

java版

思路: 以String[][] res 来保存先前状态,res[i][j] 代表str1到i、str2到j的公共串, 注意如果str1.charAt(i) != str2.charAt(j) , 则res[i][j] = "";

递推公式为:

如果 str1.charAt(i) == str2.charAt(j)

res[i][j] = str1.charAt(i-1) == str2.charAt(j-1) ? res[i-1][j-1] + str1.charAt(i) : str1.charAt(i) + "";

否则

 res[i][j] = str1.charAt(i) == str2.charAt(j) ?  str1.charAt(i) + "" : "";

注意边界i-1 < 0 和 j - 1 < 0 的处理,还有就是这种定义的状态不连续,需要设置 lcs来记录过程中的最长串

import java.util.*;
public class Solution {
    public String LCS (String str1, String str2) {
        // write code here
        int m = str1.length(), n = str2.length();
        String[][] res = new String[m][n];
        String lcs = "";
        for(int i = 0; i < m; i++)
            Arrays.fill(res[i], "");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(i - 1 >= 0 && j - 1 >= 0){
                    if(str1.charAt(i) == str2.charAt(j)){
                        res[i][j] = str1.charAt(i-1) == str2.charAt(j-1) ? res[i-1][j-1] + str1.charAt(i) : str1.charAt(i) + "";
                    }
                }else {
                    res[i][j] = str1.charAt(i) == str2.charAt(j) ?  str1.charAt(i) + "" : "";
                }
                lcs  =   res[i][j].length() > lcs.length() ? res[i][j] : lcs;
            }
        }
        return lcs;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 17:28
25届每天都在焦虑找工作的事情0offer情绪一直很低落硬撑着面了一个岗位岗位有应酬的成分面试的时候hr给我出各种场景题问的问题比较犀利&nbsp;有点压力面的感觉感觉有点回答不上来本来就压抑的情绪瞬间爆发了呢一瞬间特别想哭觉得自己特别没用没绷住掉眼泪了事后想想觉得自己挺有病的&nbsp;真的破大防了
喜欢唱跳rap小刺猬...:我觉得没关系吧,之前有一次面试leader给我压力面,我顶住了压力,结果入职的时候发现组里氛围很差,果断跑路。其实从面试就能大概看出组的情况,面试体验好的组倒是不一定好,但是面试体验不好的组。。。就很难说
点赞 评论 收藏
分享
点赞 评论 收藏
分享
05-14 09:24
青岛工学院 C++
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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