标签:
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
.
最长公共子序列的定义:
最长公共子序列问题是在一组序列(通常2个)中找到最长公共子序列(注意:不同于子串,LCS不需要是连续的子串).
State: f[i][j] 表示在字符串A中前i个字符与B字符串前j个字符的最长LCS。
Fuction: f[i][j] = max(f[i - 1][j], f[i][j - 1]) if (A[i -1] != B[j - 1]) 对应与 “abc” “ab” 和 “ab" 和”abc“。if(A[i - 1] == B[j - 1]) f[i][j] = max(f[i - 1][j], f[i][j - 1], f[i - 1][j -1] + 1).
Initialization: int [][] f = new int[A.length() + 1][B.length() + 1]
Answer:f[A.length()][B.length()]
1 public class Solution { 2 /** 3 * @param A, B: Two strings. 4 * @return: The length of longest common subsequence of A and B. 5 */ 6 public int longestCommonSubsequence(String A, String B) { 7 int m = A.length(); 8 int n = B.length(); 9 if (m == 0 || n == 0) { 10 return 0; 11 } 12 int[][] f = new int[m + 1][n + 1]; 13 for (int i = 1; i <= m; i++) { 14 for (int j = 1; j <= n; j++) { 15 f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); 16 if (A.charAt(i - 1) == B.charAt(j - 1)) { 17 f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + 1); 18 } 19 } 20 } 21 return f[m][n]; 22 } 23 }
Longest Common Subsequence (DP)
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5403103.html