Try   HackMD

Leetcode 1143. Longest Common Subsequence

tags: Leetcode(JAVA)

題目 : https://leetcode.com/problems/longest-common-subsequence/

想法 :

​​​​LCS。
​​​​
​​​​if(str[i] == str[j])
​​​​    dp[i][j]=dp[i-1][j-1]+1;
​​​​else
​​​​    dp[i][j]=max(dp[i-1][j], dp[i][j-1]);

時間複雜度 : O(n*m)。

程式碼 : (JAVA)

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int l1=text1.length(), l2=text2.length();
        int[][] dp=new int[1010][1010];
        
        for(int i=1 ; i<=l1 ; i++){
            for(int j=1 ; j<=l2 ; j++){
                if(text1.charAt(i-1) == text2.charAt(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]);
                }
            }
        }
        
        return dp[l1][l2];
    }
}