zoukankan      html  css  js  c++  java
  • LintCode-Longest Common Subsequence

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

    Your code should return the length of LCS.

    Example

    For "ABCD" and "EDCA", the LCS is "A" (or D or C), return 1

    For "ABCD" and "EACB", the LCS is "AC", return 2

    Solution:

     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 lenA = A.length(), lenB = B.length();
     8         if (lenA==0 || lenB == 0) return 0;
     9 
    10         int[][] lcs = new int[lenA+1][lenB+1];
    11         for (int i=0;i<=lenA;i++) lcs[i][0] = 0;
    12         for (int i=0;i<=lenB;i++) lcs[0][i] = 0;
    13 
    14         for (int i=1;i<=lenA;i++)
    15             for (int j=1;j<=lenB;j++){
    16                 lcs[i][j] = Math.max(lcs[i-1][j], lcs[i][j-1]);
    17                 if (A.charAt(i-1) == B.charAt(j-1) && lcs[i][j]<lcs[i-1][j-1]+1)
    18                 lcs[i][j] = lcs[i-1][j-1]+1;
    19             }
    20 
    21         return lcs[lenA][lenB];
    22     }
    23 }
  • 相关阅读:
    转盘抽奖活动代码
    信息滚动条
    gulp应用学习
    js实现语音播报功能
    如何安装使用sass
    纯CSS写三角形-border法
    css兼容性写法
    字体中英文对照
    浏览器内核判断
    个人课程总结
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4196811.html
Copyright © 2011-2022 走看看