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

    Given two strings, find the longest common subsequence (LCS).
    
    Your code should return the length of LCS.
    
    Have you met this question in a real interview? Yes
    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
    For "ABCD" and "EDCA", the LCS is "A" (or "D", "C"), return 1.
    
    For "ABCD" and "EACB", the LCS is "AC", return 2.

    状态方程时题意的转化, 通常要if, 遍历到当前状态时, 最后一个字母的情况与上一个或者上多个状态的关系

    结果是最后的状态还是只是遍历到最后的状态求全局最优

    Longest Increasing Subsequence

     public int longestCommonSubsequence(String A, String B) {
            // write your code here
            //state 
            int m = A.length(), n = B.length();
            if (m == 0 || n == 0 || A == null || B == null) {
                return 0;
            }
            int[][] res = new int[m + 1][n + 1];
            
            //initialize
            for (int i = 0; i <= m; i++) {
                res[i][0] = 0;
            }
             for (int i = 0; i <= n; i++) {
                res[0][i] = 0;
            }
            //function
            for (int i = 1; i <= m; i++) {
                for (int j = 1; j <= n; j++) {
                    if (A.charAt(i - 1) == B.charAt(j - 1)) {
                        res[i][j] = res[i - 1][j - 1] + 1;
                    } else {
                        res[i][j] = Math.max(res[i - 1][j], res[i][j - 1]);
                    }
                }
            }
            return res[m][n];
            
        }
    

      

  • 相关阅读:
    强联通 HDU 1269
    zznu 1255 数字统计(数位DP, 数学方法)
    POJ Round Numbers(数位DP)
    #1033 : 交错和
    XHXJ's LIS
    吉哥系列故事——恨7不成妻
    数字0-9的数量
    Balanced Number
    BALNUM
    F(x)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7291005.html
Copyright © 2011-2022 走看看