1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public String Lcsequence(String s1, String s2) { if(s1 == null || s2 ==null || s1.length() == 0 || s2.length() == 0) return ""; int[][] dp = new int[s1.length() + 1][s2.length() + 1]; int[][] flag = new int[s1.length() + 1][s2.length() + 1]; for(int i = 0; i < s1.length(); ++i) { for(int j = 0; j < s2.length(); ++j) { if(s1.charAt(i) == s2.charAt(j)) { dp[i + 1][j + 1] = dp[i][j] + 1; flag[i + 1][j + 1] = 1; } else if(dp[i][j + 1] >= dp[i + 1][j]) { dp[i + 1][j + 1] = dp[i][j + 1]; flag[i + 1][j + 1] = 2; } else { dp[i + 1][j + 1] = dp[i + 1][j]; flag[i + 1][j + 1] = 3; } } } System.out.println(dp[s1.length()][s2.length()]); StringBuilder tmp = new StringBuilder(); getLcs(s1, s2, s1.length(), s2.length(), flag, tmp); return tmp.toString(); }
public void getLcs(String s1, String s2, int len1, int len2, int[][] flag, StringBuilder tmp) { if(len1 < 1 || len2 < 1) return; if(flag[len1][len2] == 1) { getLcs(s1,s2, len1 - 1, len2 - 1, flag, tmp); tmp.append(s1.charAt(len1 - 1)); } else if(flag[len1][len2] == 2) getLcs(s1,s2, len1 - 1, len2, flag, tmp); else if(flag[len1][len2] == 3) getLcs(s1,s2, len1, len2 - 1, flag, tmp); }
|