Advertisement
ogv

Untitled

ogv
Jan 6th, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4. private static String solve(String s, String t) {
  5. char[] sa = s.toCharArray();
  6. char[] ta = t.toCharArray();
  7. int[][] lcsLen = new int[sa.length+1][ta.length+1];
  8.  
  9. for (int i = 0; i < sa.length; i++)
  10. for (int j = 0; j < ta.length; j++) {
  11. if (sa[i] == ta[j]) lcsLen[i+1][j+1] = 1 + lcsLen[i][j];
  12. else lcsLen[i+1][j+1] = Math.max(lcsLen[i+1][j], lcsLen[i][j+1]);
  13. }
  14.  
  15. int maxLen = lcsLen[sa.length-1][ta.length-1];
  16. if (maxLen == 0) return "";
  17. char[] lcs = new char[maxLen+1];
  18.  
  19. int i = sa.length;
  20. int j = ta.length;
  21. int k = maxLen;
  22. while (k >= 0) {
  23. if (j > 0 && lcsLen[i][j] == lcsLen[i][j-1]) j--;
  24. else if (i > 0 && lcsLen[i][j] == lcsLen[i-1][j]) i--;
  25. else {
  26. lcs[k--] = sa[i-1];
  27. i--;
  28. j--;
  29. }
  30. }
  31.  
  32. return new String(lcs);
  33. }
  34.  
  35. public static void main(String[] args) {
  36. String s, t;
  37. try (Scanner scanner = new Scanner(System.in)) {
  38. s = scanner.nextLine();
  39. t = scanner.nextLine();
  40. }
  41.  
  42. String result = solve(s, t);
  43. System.out.println(result);
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement