Java实现-最长公共子序列

来源:互联网 发布:filereader读取文件php 编辑:程序博客网 时间:2024/05/21 22:12

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) {        // write your code here        if(A.length()==0||B.length()==0){return 0;}int dp[][]=new int[A.length()+1][B.length()+1];for(int i=0;i<A.length()+1;i++){dp[0][i]=0;}for(int i=0;i<B.length()+1;i++){dp[i][0]=0;}for(int i=0;i<A.length();i++){for(int j=0;j<B.length();j++){if(A.charAt(i)==B.charAt(j)){dp[i+1][j+1]=dp[i][j]+1;}else{dp[i+1][j+1]=Math.max(dp[i+1][j], dp[i][j+1]);}}}return dp[A.length()][B.length()];    }}



原创粉丝点击