The Longest Common Consecutive Subsequence of X and Y 最长公共连续子数列/最长公共连续子序列

Description

Given 2 arrays X and Y, return the MAXIMUM length of the longest common consecutive subsequence. If no such subsequence exists, return 0.

A consecutive subsequence of X is a slice of X, which means X[i:j], 0≤i<j≤length(X)−10≤i<j≤length(X)−1.

X and Y only contain integers.

Sample Input

Two lines of string forms of arrays (split by space).

1 5 7 3 4 5
7 3 4 4 5 7 -2

Sample Output

An integer.

3

Explanation of Sample

Explanation: The longest common consecutive subsequence is [7,3,4] (X[2:4] and Y[0:2])

Constraints of 10 test cases

Case 1: 1<X.length, Y.length<10

Case 2-4: 1<X.length, Y.length<300

Case 5-7: 1<X.length, Y.length<3000

Case 8-10: 1<X.length, Y.length<10000

#include <vector>
#include <iostream>
using namespace std;

int findLength(vector<int> a,vector<int> b){
    int c[2][10005];
    int bi;
    int MXL = -1;
    for(int i=0;i<a.size();i++){
        bi = i&1;
        for (int j=0;j <= b.size();j++){
            if(i==0||j==0)
                c[bi][j]=0;
            else if(a[i]==b[j-1]){
                c[bi][j] = c[1-bi][j-1]+1;
                if(c[bi][j] > MXL)
                    MXL=c[bi][j];
            }
            else
                c[bi][j] = 0;
        }
    }
    return MXL;
}

int main(){
    vector<int> a;
    vector<int> b;
    int i = 0;
    while (cin >> i) {
        a.push_back(i);
        char ch = getchar();
        if (ch == '\n')
            break;
    }
    while (cin >> i) {
        b.push_back(i);
        char ch = getchar();
        if (ch == '\n')
            break;
    }
    cout << findLength(a, b) << "\n";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值