iT邦幫忙

2024 iThome 鐵人賽

0
佛心分享-刷題不只是刷題

刷經典 LeetCode 題目系列 第 37

經典LeetCode 1143. Longest Common Subsequence

  • 分享至 

  • xImage
  •  

題目:
給定兩個字串 text1text2,回傳兩個字串的最長公共子序列的長度。

  • 子序列是指一個字串中刪除某些(或不刪除任何)字元後剩下的字元序列,並且順序保持不變。
  • 公共子序列是兩個字串都包含的一個子序列。

範例:

Input: text1 = "abcde", text2 = "ace"
Output: 3  
Explanation: 最長的公共子序列是 "ace",因此長度為 3。
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: 最長的公共子序列是 "abc",因此長度為 3。
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: 兩個字串沒有共同的子序列,因此長度為 0。

限制條件

  • 1 <= text1.length, text2.length <= 1000
  • text1text2 由小寫英文字母組成

解題思路

實作:

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int m = text1.size();
        int n = text2.size();
        
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (text1[i - 1] == text2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        return dp[m][n];
    }
};

參考:
#1143. Longest Common Subsequence


上一篇
經典LeetCode 300. Longest Increasing Subsequence
系列文
刷經典 LeetCode 題目37
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言