码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Common Subsequence

时间:2019-12-21 22:27:26      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:htm   red   find   org   ini   char   com   input   commons   

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

标签:htm   red   find   org   ini   char   com   input   commons   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!