最长公共子序列(LCS)
POJ-Prob.1458 看算法导论3 自己用java写的,flag可以不用,课后题要求用min(m,n)+O(1)的空间完成...改天再写.
1 import java.util.Scanner; 2 3 /** 4 * Created by IntelliJ IDEA. 5 * User: mayday 6 * Date: 13-2-15 7 * Time: 下午5:03 8 */ 9 public class Main { 10 public static int m, n; 11 12 public static void main(String[] args) { 13 Scanner scanner = new Scanner(System.in); 14 String str1 = scanner.next(); 15 String str2 = scanner.next(); 16 m = str1.length(); 17 n = str2.length(); 18 Print_LCS(Length_Of_LCS(str1, str2), str1, m, n); 19 } 20 21 private static void Print_LCS(int[][] b, String str1, int i, int j) { 22 if (i == 0 || j == 0) 23 return; 24 if (b[i][j] == 2) { 25 Print_LCS(b, str1, i - 1, j - 1); 26 System.out.print(str1.charAt(i - 1)); 27 } else if (b[i][j] == 1) 28 Print_LCS(b, str1, i - 1, j); 29 else 30 Print_LCS(b, str1, i, j - 1); 31 } 32 33 private static int[][] Length_Of_LCS(String str1, String str2) { 34 35 int c[][] = new int[m + 1][n + 1]; 36 int flag[][] = new int[m + 1][n + 1]; 37 for (int i = 0; i <= m; i++) { 38 c[i][0] = 0; 39 flag[i][0] = 0; 40 } 41 for (int j = 0; j <= n; ++j) { 42 c[0][j] = 0; 43 flag[0][j] = 0; 44 } 45 for (int i = 1; i <= m; i++) 46 for (int j = 1; j <= n; j++) { 47 if (str1.charAt(i - 1) == str2.charAt(j - 1)) { 48 c[i][j] = c[i - 1][j - 1] + 1; 49 flag[i][j] = 2; 50 } else { 51 c[i][j] = Math.max(c[i - 1][j], c[i][j - 1]); 52 if (c[i - 1][j] >= c[i][j - 1]) { 53 flag[i][j] = 1; 54 } 55 } 56 } 57 return flag; 58 } 59 }