|
| 1 | +package nowcoder; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Scanner; |
| 5 | +import java.util.Set; |
| 6 | + |
| 7 | +/** |
| 8 | + * Created by jacob on 2019-07-24. |
| 9 | + */ |
| 10 | +public class LCS { |
| 11 | + public static void main(String[] args) { |
| 12 | + LCS main = new LCS(); |
| 13 | + Scanner scanner = new Scanner(System.in); |
| 14 | + while (scanner.hasNextLine()) { |
| 15 | + String[] strings = scanner.nextLine().split(" "); |
| 16 | + System.out.println(main.longestCommonSequence(strings[0], strings[1])); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + private Set<String> longestCommonSequence(String a, String b) { |
| 21 | + if (a.length() == 0 || b.length() == 0) { |
| 22 | + return null; |
| 23 | + } |
| 24 | + int[][] dp = new int[a.length() + 1][b.length() + 1]; |
| 25 | + char[] aChars = a.toCharArray(); |
| 26 | + char[] bChars = b.toCharArray(); |
| 27 | + for (int i = 0; i < a.length(); i++) { |
| 28 | + for (int j = 0; j < b.length(); j++) { |
| 29 | + if (aChars[i] == bChars[j]) { |
| 30 | + dp[i + 1][j + 1] = dp[i][j] + 1; |
| 31 | + } else { |
| 32 | + dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]); |
| 33 | + } |
| 34 | + } |
| 35 | + } // 将二维数组的数据全部填充完毕 |
| 36 | + |
| 37 | + Set<String> result = new HashSet<>(); |
| 38 | + this.printCommonSequeue(aChars, bChars, dp, "", result, a.length(), b.length()); |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | + private void printCommonSequeue(char[] aChars, char[] bChars, int[][] dp, |
| 43 | + String initStr, Set<String> result, |
| 44 | + int i, int j) { |
| 45 | + StringBuilder stringBuilder = new StringBuilder(initStr); |
| 46 | + while (i > 0 && j > 0) { |
| 47 | + if (aChars[i - 1] == bChars[j - 1]) { |
| 48 | + stringBuilder.append(aChars[i - 1]); |
| 49 | + i--; |
| 50 | + j--; |
| 51 | + } else { |
| 52 | + if (dp[i][j - 1] > dp[i - 1][j]) { |
| 53 | + j--; |
| 54 | + } else if (dp[i][j - 1] < dp[i - 1][j]) { |
| 55 | + i--; |
| 56 | + } else { |
| 57 | + this.printCommonSequeue(aChars, bChars, dp, stringBuilder.toString(), result, i - 1, j); |
| 58 | + j--; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + result.add(stringBuilder.reverse().toString()); |
| 63 | + } |
| 64 | +} |
0 commit comments