标签:
1 2 import java.util.Random; 3 4 public class LCS{ 5 public static void main(String[] args){ 6 7 //设置字符串长度 8 int substringLength1 = 20; 9 int substringLength2 = 20; //具体大小可自行设置 10 11 // 随机生成字符串 12 String x = GetRandomStrings(substringLength1); 13 String y = GetRandomStrings(substringLength2); 14 15 Long startTime = System.nanoTime(); 16 // 构造二维数组记录子问题x[i]和y[i]的LCS的长度 17 int[][] opt = new int[substringLength1 + 1][substringLength2 + 1]; 18 19 // 动态规划计算所有子问题 20 for (int i = substringLength1 - 1; i >= 0; i--){ 21 for (int j = substringLength2 - 1; j >= 0; j--){ 22 if (x.charAt(i) == y.charAt(j)) 23 opt[i][j] = opt[i + 1][j + 1] + 1; //参考上文我给的公式。 24 else 25 opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]); //参考上文我给的公式。 26 } 27 } 28 29 ------------------------------------------------------------------------------------- 30 31 理解上段,参考上文我给的公式: 32 33 根据上述结论,可得到以下公式, 34 35 如果我们记字符串Xi和Yj的LCS的长度为c[i,j],我们可以递归地求c[i,j]: 36 37 / 0 if i<0 or j<0 38 c[i,j]= c[i-1,j-1]+1 if i,j>=0 and xi=xj 39 / max(c[i,j-1],c[i-1,j] if i,j>=0 and xi≠xj 40 41 ------------------------------------------------------------------------------------- 42 43 System.out.println("substring1:"+x); 44 System.out.println("substring2:"+y); 45 System.out.print("LCS:"); 46 47 int i = 0, j = 0; 48 while (i < substringLength1 && j < substringLength2){ 49 if (x.charAt(i) == y.charAt(j)){ 50 System.out.print(x.charAt(i)); 51 i++; 52 j++; 53 } else if (opt[i + 1][j] >= opt[i][j + 1]) 54 i++; 55 else 56 j++; 57 } 58 Long endTime = System.nanoTime(); 59 System.out.println(" Totle time is " + (endTime - startTime) + " ns"); 60 } 61 62 //取得定长随机字符串 63 public static String GetRandomStrings(int length){ 64 StringBuffer buffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz"); 65 StringBuffer sb = new StringBuffer(); 66 Random r = new Random(); 67 int range = buffer.length(); 68 for (int i = 0; i < length; i++){ 69 sb.append(buffer.charAt(r.nextInt(range))); 70 } 71 return sb.toString(); 72 } 73 }
标签:
原文地址:http://www.cnblogs.com/david-wang/p/4340249.html