Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. package com.dnajdrowski;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5.  
  6. public class Main {
  7.  
  8. public static void main(String[] args) {
  9. Scanner s = new Scanner(System.in);
  10. System.out.print("Podaj pierszy ciąg: ");
  11. String x = s.nextLine();
  12. System.out.print("Podaj drugi ciąg: ");
  13. String y = s.nextLine();
  14. int[][] c = new int[x.length() + 1][y.length() + 1];
  15. String[][] b = new String[x.length() + 1][y.length() + 1];
  16. LCS_LENGTH(x, y, c, b);
  17. System.out.print("LCS = ");
  18. PrintLCS(x, y, b, x.length(), y.length());
  19. }
  20.  
  21. public static void LCS_LENGTH(String x, String y, int[][] c, String[][] b) {
  22. int m = x.length();
  23. int n = y.length();
  24.  
  25. for (int i = 0; i <= m; i++)
  26. c[i][0] = 0;
  27. for (int j = 0; j <= n; j++)
  28. c[0][j] = 0;
  29.  
  30. for (int i = 1; i <= m; i++) {
  31. for (int j = 1; j <= n; j++) {
  32. if (x.charAt(i-1) == y.charAt(j-1)) {
  33. c[i][j] = c[i-1][j-1] + 1;
  34. b[i][j] = "\\";
  35. } else {
  36. if(c[i][j-1] > c[i-1][j]) {
  37. c[i][j] = c[i][j-1];
  38. b[i][j] = "-";
  39. } else {
  40. c[i][j] = c[i-1][j];
  41. b[i][j] = "|";
  42. }
  43. }
  44. }
  45. }
  46. }
  47.  
  48.  
  49. public static void PrintLCS(String x, String y, String[][] b, int i, int j) {
  50. if(i == 0 || j == 0) {
  51. return;
  52. }
  53. if(b[i][j].equals("\\")) {
  54. PrintLCS(x, y, b, i-1, j-1);
  55. System.out.print(x.charAt(i-1));
  56. }else if(b[i][j].equals("|"))
  57. PrintLCS(x, y, b, i-1, j);
  58. else
  59. PrintLCS(x, y, b, i, j-1);
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement