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

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[] s1Arr = s1.toCharArray();
        char[] s2Arr = s2.toCharArray();
        if (s1Arr.length == 0 || s2Arr.length==0){
            return "-1";
        }
        String[][]dp = new String[s1Arr.length][s2Arr.length];
	  	// dp[i][j] : s1[0--i]与s2[0--j]的最长公共字符串
        // dp[i][j] = dp[i-1][j-1] + s1Arr[i] ;if (s1Arr[i] ==s2Arr[j])
        // 			= Math.maxLength(dp[i][j-1] ,dp[i-1][j]);


        for (int i = 0 ; i < s1Arr.length; i++) {
            for (int j = 0 ; j < s2Arr.length; j++) {
                if (i == 0 && j == 0) {
                    dp[0][0] = s1Arr[0] == s2Arr[0] ? "" + s1Arr[0] : "";
                    continue;
                }
                if (i == 0) {
                    if (s1Arr[0] == s2Arr[j]) {
                        dp[0][j] = "" + s1Arr[0];
                    } else {
                        dp[0][j] =  dp[0][j - 1];
                    }
                    continue;
                }
                if (j == 0 ) {
                    if (s1Arr[i] == s2Arr[0]) {
                        dp[i][0] = "" + s1Arr[i];
                    } else {
                        dp[i][0] =  dp[i-1][0];
                    }
                    continue;
                }
                if (s1Arr[i] == s2Arr[j]) {
                    dp[i][j] = dp[i - 1][j - 1] + s1Arr[i];
                } else {
                    dp[i][j] =
                        dp[i][j - 1].length() > dp[i - 1][j].length()
                        ? dp[i][j - 1] : dp[i - 1][j];
                }

            }
        }

        return dp[s1Arr.length - 1][s2Arr.length - 1] == "" ? "-1" : dp[s1Arr.length -
                1][s2Arr.length - 1] ;

    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务