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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,766评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,788评论 0 23
  • #1996 AHSME ##1996 AHSME Problems/Problem 1 The addition ...
    abigtreenj阅读 1,430评论 0 0
  • 我没有名字,年龄不详,代号DR2。 1 6点,闹铃响了。我像往常一样起床、穿衣、洗漱。 那个暂且叫做“妈妈”的女人...
    施页阅读 574评论 4 26
  • “你买那么多只鞋干嘛?坑货!”“我朋友说多出几只鞋跑得快点的啊!”“等下举报这个250!”不久后就出来一声好听但悲...
    夏檬懵阅读 467评论 17 8