Description
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
Example 1: Input: "ABCD" and "EDCA" Output: 1 Explanation: LCS is 'A' or 'D' or 'C' Example 2: Input: "ABCD" and "EACB" Output: 2 Explanation: LCS is "AC"
思路:Dp[i][j] 表示A序列前i个数,与B的前j个数的LCS长度。
对A的每个位置i,枚举B的每个位置j。
public class Solution { /** * @param A: A string * @param B: A string * @return: The length of longest common subsequence of A and B */ public int longestCommonSubsequence(String A, String B) { int n = A.length(); int m = B.length(); int f[][] = new int[n + 1][m + 1]; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); if(A.charAt(i - 1) == B.charAt(j - 1)) f[i][j] = f[i - 1][j - 1] + 1; } } return f[n][m]; } }