最長公共子序列2

描述

給定兩個字符串str1和str2,輸出兩個字符串的最長公共子序列。如果最長公共子序列為空,則返回"-1"。目前給出的數(shù)據(jù),僅僅會存在一個最長的公共子序列

image.png

思路:
1、定義dp[i][j] 其中dp[i][j]表示在s1中以i結(jié)尾,s2中以j結(jié)尾的字符串的最長公共子序列字符串。
2、若是i位與j位的字符相等,則該問題可以變成s.charAt(i)+dp[i?1][j?1],
3、若是i位與j位的字符不相等,則對比 dp[i?1][j],dp[i][j-1]誰的字符串長,就取誰的結(jié)果

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) {
        int length1 =s1.length();
        int length2 =s2.length();
        String[][]dp=new String[length1+1][length2+1];
        for(int i = 0;i<=length1;i++){
            for(int j = 0;j<=length2;j++){
                if(i == 0||j==0){dp[i][j] = "";}
                else if(s1.charAt(i-1) == s2.charAt(j-1)){
                  dp[i][j] = dp[i-1][j-1]+s1.charAt(i-1);
                }else{
                   if(dp[i-1][j].length()>dp[i][j-1].length()) {
                       dp[i][j] =  dp[i-1][j];
                   }else{
                       dp[i][j] =  dp[i][j-1]; 
                   }
                }
            }
        }
        if(dp[length1][length2]=="") return "-1";
        return dp[length1][length2];
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容