Advertisement
GokulDeep

longestCommonSubsequence

Dec 15th, 2024
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. public static List<Integer> longestCommonSubsequence(List<Integer> a, List<Integer> b) {
  2. List<Integer> ans = new ArrayList<>();
  3. int m = a.size() + 1;
  4. int n = b.size() + 1;
  5. int[][] arr = new int[m][n];
  6. if (a.size() < 0 || b.size() < 0) {
  7. return ans;
  8. }
  9. for (int i = 1; i <= m - 1; i++) {
  10. for (int j = 1; j <= n - 1; j++) {
  11. if (a.get(i - 1) != null && b.get(j - 1) != null && a.get(i - 1) == b.get(j - 1)) {
  12. arr[i][j] = arr[i - 1][j - 1] + 1;
  13. } else {
  14. arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
  15. }
  16. }
  17. }
  18. int i = a.size();
  19. int j = b.size();
  20. while (i > 0 && j > 0) {
  21. if (a.get(i - 1) != null && b.get(j - 1) != null && a.get(i - 1) == b.get(j - 1)) {
  22. ans.add(a.get(i - 1));
  23. i--;
  24. j--;
  25. } else if (arr[i][j] == arr[i][j - 1]) {
  26. j--;
  27. } else {
  28. i--;
  29. }
  30. }
  31. Collections.reverse(ans);
  32. return ans;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement