Longest Common Subsequence

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

Your code should return the length of LCS.

Clarification

What's the definition of Longest Common Subsequence?

https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

http://baike.baidu.com/view/2020307.htm

Example

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

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

Solution

单序列型研究如何切,双序列型研究最后一个数字或者字母。

双序列型动态规划

图加上故事,非常有助于记忆。

abcd = abcd then f[i - 1][j - 1] + 1

state: f[i][j]代表了第一个sequence的前i个数字/字符,配上第二个sequence的前j个... function: f[i][j] =研究第i个和第j个的匹配关系 initialize: f[i][0]和f[0][i]

answer: f[s1.length()][s2.length()]

state: f[i][j]表示前i个字符配上前j个字符的LCS的长度 function: f[i][j] = MAX(f[i-1][j], f[i][j-1], f[i-1][j-1] + 1) // a[i] == b[j]

= MAX(f[i-1][j], f[i][j-1]) // a[i] != b[j] intialize: f[i][0] = 0 f[0][j] = 0

answer: f[a.length()][b.length()]

Last updated

Was this helpful?