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

最长公共子序列(二)

https://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) {
        StringBuilder[][] sbs = new StringBuilder[s1.length() + 1][s2.length() + 1];

        for (int i = 0; i != s1.length() + 1; ++i) {
            for (int j = 0; j != s2.length() + 1; ++j) {
                sbs[i][j] = new StringBuilder();
            }
        }

        for (int i = 0; i != s1.length(); ++i) {
            for (int j = 0; j != s2.length(); ++j) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(j);
                if (c1 == c2) {
                    sbs[i + 1][j + 1].append(sbs[i][j].toString()).append(c1);
                } else if (sbs[i][j + 1].length() > sbs[i + 1][j].length()) {
                    sbs[i + 1][j + 1].append(sbs[i][j + 1].toString());
                } else {
                    sbs[i + 1][j + 1].append(sbs[i + 1][j].toString());
                }
            }
        }
        if (sbs[s1.length()][s2.length()].length() == 0) {
            return "-1";
        }
        return sbs[s1.length()][s2.length()].toString();
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务