package com.wentora.exercise; /** * 求解最大公共子序列长度 * @author wentora */ import java.util.Scanner; public class LSD { private String a; private String b; private int[][] c; LSD(String a, String b) { this.a = a; this.b = b; c = new int[a.length() + 1][b.length() + 1]; } /*递归求解最大子串长度 * public int getLSD(int i, int j) { if(i == 0 || j == 0) return 0; else if(a.charAt(i - 1) == b.charAt(j - 1)) return getLSD(i - 1, j - 1) + 1; else if(getLSD(i - 1, j) > getLSD(i, j - 1)) return getLSD(i - 1 ,j); else return getLSD(i, j - 1); }*/ //动态规划求解 public int getLSD(int i, int j) { for(int m = 1; m < i; m++) c[m][0] = 0; for(int n = 0; n < j; n++) c[0][n] = 0; for(int m = 1; m <= i; m ++) for(int n = 1; n <= j; n++) { if(a.charAt(m - 1) == b.charAt(n - 1)) c[m][n] = c[m - 1][n - 1] + 1; else if(c[m][n - 1] > c[m - 1][n]) c[m][n] = c[m][n - 1]; else c[m][n] = c[m - 1][n]; } return c[i][j]; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); System.out.print("please input string a : "); String c ; c = scan.next(); System.out.print("please input string b : "); String d ; d = scan.next(); LSD lsd = new LSD(c,d); System.out.print("The LSD length is : " + lsd.getLSD(c.length() , d.length() )); } }