题解 | #最长公共子序列(二)#

最长公共子序列(二)

http://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11

import java.util.*;


public class Solution {
    /**
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String s1, String s2) {
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        int[][] dp = new int[c1.length + 1][c2.length + 1];
        for (int i = 1; i <= c1.length; i++) {
            for (int j = 1; j <= c2.length; j++) {
                if (c1[i - 1] == c2[j - 1]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        if (dp[c1.length][c2.length] == 0){
            return "-1";
        }
        int curRow = c1.length;
        int curCol = c2.length;
        String ans = "";
        while (curRow > 0 && curCol >0 && dp[curRow][curCol] != 0){
            while (dp[curRow][curCol] == dp[curRow][curCol - 1]){
                curCol--;
            }
            while (dp[curRow][curCol] == dp[curRow - 1][curCol]){
                curRow--;
            }
            ans = c1[curRow - 1] + ans;
            curRow--;
            curCol--;
        }
        return ans;
    }
}
全部评论

相关推荐

半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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