赞
踩
- public class Test1 {
-
- public static void main(String[] args) {
- char[] chars1 = "ABCBDAB".toCharArray();
- char[] chars2 = "BDCABA".toCharArray();
- LCS(chars1, chars2);
- }
-
- public static void LCS(char[] chars1, char[] chars2) { // 最长公共子序列
- int len1 = chars1.length;
- int len2 = chars2.length;
- int[][] dp = new int[len1+1][len2+1];
- dp[0][0] = 0;
- for(int i = 1; i <= len1; i++) {
- for(int j = 1; j <= len2; j++) {
- if(chars1[i-1] == chars2[j-1]) {
- dp[i][j] = dp[i-1][j-1] + 1;
- }
- else {
- dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
- }
- }
- }
- // System.out.println(dp[len1][len2]); // 最长公共子序列长度
- getres(dp, len1, len2, chars1);
- }
-
- public static void getres(int[][] dp, int i, int j, char[] chars) {
- StringBuilder sb = new StringBuilder();
- while(i != 0 && j != 0) {
- if(dp[i][j] == dp[i-1][j]) i--;
- else if(dp[i][j] == dp[i][j-1]) j
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。