zoukankan      html  css  js  c++  java
  • 最长公共子序列问题

    package com.hzins.suanfa;
    /**
     * 最长公共子序列问题
     * @author Administrator
     *
     */
    public class Demo5 {
        /**
         * 额外空间复杂度O(n^2)
         * @param str1
         * @param str2
         * @return
         */
        public static int[][] getdp(char[] str1, char[] str2){
            int[][] dp = new int[str1.length][str2.length];
            dp[0][0] = str1[0] == str2[0] ? 1 : 0;
            for(int i = 1;i < str1.length; i++){
                dp[i][0] = Math.max(dp[i - 1][0], str1[i] == str2[0] ? 1 : 0);
            }
            for(int j = 1;j < str2.length; j++){
                dp[0][j] = Math.max(dp[0][j - 1], str1[0] == str2[j] ? 1 : 0);
            }
            for(int i = 1;i < str1.length;i ++){
                for(int j = 1;j < str2.length; j ++){
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                    if(str1[i] == str2[j]){
                        dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
                    }
                }
            }
            return dp;
        }
        /**
         * 额外空间复杂度O(n)
         * @param str1
         * @param str2
         * @return
         */
        public static int[] getdp1(char[] str1, char[] str2){
            int[] dp = new int[str2.length];
            dp[0] = str1[0] == str2[0] ? 1 : 0;
            for(int i = 1;i < str2.length;i ++){
                dp[i] = Math.max((str1[0] == str2[0] ? 1 : 0), dp[i - 1]);
            }
            for(int i = 1;i < str1.length;i ++){
                dp[0] = Math.max((str1[i] == str2[0] ? 1 : 0), dp[0]);
                for(int j = 1;j < str2.length; j ++){
                    if(str1[i] == str2[j]){
                        dp[j] = dp[j - 1] + 1;
                    }
                    dp[j] = Math.max(dp[j - 1], dp[j]);
                }
            }
            return dp;
        }
        public static void main(String[] args) {
            String str1 = "1234567";
            String str2 = "456789";
            int[] dp = getdp1(str1.toCharArray(), str2.toCharArray());
            System.out.println(dp[dp.length - 1]);
    //        int[][] dp = getdp(str1.toCharArray(), str2.toCharArray());
    //        System.out.println(dp[dp.length - 1][dp[0].length - 1]);
        }
    }
  • 相关阅读:
    关于java.lang.OutOfMemoryError: Java heap space的错误分析
    对TCP/IP网络协议的深入浅出归纳
    leetcode面试准备:Contains Duplicate I && II
    leetcode面试准备:Count Complete Tree Nodes
    leetcode面试准备: Jump Game II
    leetcode面试准备: Jump Game
    LeetCode解题报告:Linked List Cycle && Linked List Cycle II
    最小栈的实现与优化
    面试:归并排序
    leetcode面试准备:Decode Ways
  • 原文地址:https://www.cnblogs.com/caobojia/p/6812376.html
Copyright © 2011-2022 走看看