首页 > 其他 > 详细

Longest Common Subsequence

时间:2019-12-21 22:00:20      阅读:90      评论:0      收藏:0      [点我收藏+]

Description

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

Your code should return the length of LCS.

Clarification

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];
    }
}

  



Longest Common Subsequence

原文:https://www.cnblogs.com/FLAGyuri/p/12078372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!