long common subsequence

Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.

Example
For "ABCD" and "EDCA", the LCS is "A" (or "D", "C"), return 1.

For "ABCD" and "EACB", the LCS is "AC", return 2.

#include <iostream>
#include <vector>
#pragma GCC diagnostic error "-std=c++11"

using namespace std;

class Solution{
public:
    int subsequence(string &m,string &n){
        
        return tryString(m,n,m.size()-1,n.size()-1);
    }
private:
    int tryString(string &m,string &n,int i,int j){
        if(i==-1 || j==-1){
            return 0;
        }
        if(m[i]==n[j]){
            return 1+max(tryString(m,n,i-1,j),tryString(m,n,i,j-1));
        } else{
            return max(tryString(m,n,i-1,j),tryString(m,n,i,j-1));
        }
    }       
};

int main(){
    string m="abc";
    string n="abdc";
    cout<<Solution().subsequence(m,n)<<endl;
    return 0;
}
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    /**
     * @param A, B: Two strings.
     * @return: The length of longest common subsequence of A and B.
     */
    int longestCommonSubsequence(string &A, string &B) {
        int az=A.size();
        int bz=B.size();
        if(az==0 || bz==0){
            return 0;
        }

        //init dp

        vector<vector<int>> dp(az+1,vector<int>(bz+1,0));
        //dp[1][1]=(A[1]==B[1] ? 1:0);

        for(int i=1;i<=az;i++){
            for(int j=1;j<=bz;j++){
                //string begin 0
                if(A[i-1]==B[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[az][bz];

    }
};

int main(){
    string A="ACBDEA";
    string B="ABCDA";

    cout<<Solution().longestCommonSubsequence(A,B);
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,931評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,220評論 0 23
  • #1996 AHSME ##1996 AHSME Problems/Problem 1 The addition ...
    abigtreenj閱讀 1,611評論 0 0
  • 我沒有名字,年齡不詳,代號DR2。 1 6點(diǎn),鬧鈴響了。我像往常一樣起床、穿衣、洗漱。 那個(gè)暫且叫做“媽媽”的女人...
    施頁閱讀 596評論 4 26
  • “你買那么多只鞋干嘛?坑貨!”“我朋友說多出幾只鞋跑得快點(diǎn)的??!”“等下舉報(bào)這個(gè)250!”不久后就出來一聲好聽但悲...
    夏檬懵閱讀 599評論 17 8

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