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

最长公共子序列(二)

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) {
        // write code here
        
        int[][]dp = new int[s1.length() + 1][s2.length() + 1];
        for (int i = 0; i < s1.length(); i ++) {
            for (int j = 0; j < s2.length(); j++) {
                if (s1.charAt(i) == s2.charAt(j)) {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                } else {
                    dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
                }
            }
        }
        
        StringBuilder result = new StringBuilder();
        int i = s1.length(), j = s2.length();
        while(i != 0 && j != 0) {
            if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                result.append(s1.charAt(i - 1));
                j--;
                i--;
            } else if (dp[i - 1][j] > dp[i][j - 1]) {
                i--;
            } else {
                j--;
            }
        }
        if (result.length() == 0) {
            return "-1";
        }
        System.out.print(result);
        return result.reverse().toString();
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
数开小菜鸡_暂退沉淀版:大二第三段,还是字节,这下真得点点举办了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务