Common Subsequence

Interview

Time limit1sMemory limit128 MB

Summary
Compute the length of the longest common subsequence of two given strings for multiple test cases.
Level

Medium4 of 10

Topics
Dynamic programming, String
Solved
No attempts yet

Problem

A subsequence of a given sequence is that sequence with zero or more of its elements left out. Formally, given a sequence X=⟨x1,x2,…,xm⟩X = \langle x_1, x_2, \ldots, x_m \rangle, a sequence Z=⟨z1,z2,…,zk⟩Z = \langle z_1, z_2, \ldots, z_k \rangle is a subsequence of XX if there is a strictly increasing sequence of indices ⟨i1,i2,…,ik⟩\langle i_1, i_2, \ldots, i_k \rangle such that xij=zjx_{i_j} = z_j for every j=1,2,…,kj = 1, 2, \ldots, k. For example, Z=⟨a,b,f,c⟩Z = \langle a, b, f, c \rangle is a subsequence of X=⟨a,b,c,f,b,c⟩X = \langle a, b, c, f, b, c \rangle via the index sequence ⟨1,2,4,6⟩\langle 1, 2, 4, 6 \rangle.

Given two sequences XX and YY, find the length of a longest common subsequence of XX and YY (a sequence that is a subsequence of both).

Input

The input contains several data sets and continues until end of file. Each data set consists of two strings, each representing one sequence. The two strings of a data set, and consecutive data sets, are separated by any amount of white space (spaces, tabs, or newlines). Each string has length at most 200200. The input is guaranteed to be well-formed.

Output

For each data set, print on its own line the length of a longest common subsequence of the two sequences.

Examples1

  1. Example 1

    Input
    abcfbc abfcab
    programming contest
    abcd mnp
    
    Expected output
    4
    2
    0