Longest 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.
Clarification
View Code
What's the definition of Longest Common Subsequence?
- https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
- http://baike.baidu.com/view/2020307.htm
SOLUTION :
先看问题,比较经典的dp问题,问length of LCS,两个string都要纪录,开一个二维数组纪录dp过程。
状态: f(x,y) A的前x跟B的前y个字母的最长LCS。
方程:既然是LCS,就要看A,B最后一位是否相同。
1,A(i) == B(j) == > f(i, j) = f (i - 1, j - 1) + 1
2, else ==> f (i,j) = f (i - 1, j) / f(i, j - 1) [就是要不然把A的最后一位扔掉,要不就把B的最后一位扔掉,看剩下的是否匹配]
初始化: 都是0就可以,所以不需要初始化,系统自动的
答案:f(A.len, B.len)

public class Solution {
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
public int longestCommonSubsequence(String A, String B) {
int[][] result = new int[A.length() + 1][B.length() + 1];
if (A == null || B == null){
return 0;
}
//function
//A[i] == B[j] ==> f(i, j) = f(i - 1, j - 1) + 1
//A[i] != B[j] ==> f(i, j) = f(i - 1, j) / f(i, j - 1)
for (int i = 1; i <= A.length(); i++){
for (int j = 1; j <= B.length(); j++){
if (A.charAt(i - 1) == B.charAt(j - 1)){
result[i][j] = result[i - 1][j - 1] + 1;
} else {
result[i][j] = Math.max(result[i - 1][j], result[i][j - 1]);
}
}
}
return result[A.length()][B.length()];
}
}
来源:https://www.cnblogs.com/tritritri/p/4955102.html
