标签:public out min tor package class demo get auth
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]); } }
标签:public out min tor package class demo get auth
原文地址:http://www.cnblogs.com/caobojia/p/6812376.html