Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. public class Main {
  2.  
  3. public static void getLCS(String x, String y) {
  4. int m = x.length();
  5. int n = y.length();
  6. int[][] Mango = new int[m + 1][n + 1];
  7.  
  8. for (int i = 0; i <= m; i++) {
  9. for (int j = 0; j <= n; j++) {
  10. if (i == 0 || j == 0)
  11. Mango[i][j] = 0;
  12. else if (x.charAt(i - 1) == y.charAt(j - 1))
  13. Mango[i][j] = 1 + Mango[i - 1][j - 1];
  14. else
  15. Mango[i][j] = Math.max(Mango[i - 1][j], Mango[i][j - 1]);
  16.  
  17. }
  18. }
  19. //printLCS
  20. int index = Mango[m][n];
  21. int tmp = index;
  22.  
  23. char[] lcs = new char[index + 1];
  24. lcs[index] = ' ';
  25.  
  26. int i = m, j = n;
  27.  
  28. while(i > 0 && j > 0) {
  29. if (x.charAt(i - 1) == y.charAt(j - 1)) {
  30. lcs[index - 1] = x.charAt(i - 1);
  31. i--;
  32. j--;
  33. index--;
  34. }
  35. else if (Mango[i - 1][j] > Mango[i][j - 1])
  36. i--;
  37. else
  38. j--;
  39. }
  40. System.out.print("NWP: ");
  41. for (int k = 0; k <= tmp; k++)
  42. System.out.print(lcs[k]);
  43. System.out.println("\nDługość NWP = " + Mango[m][n] + "\n");
  44. }
  45.  
  46. public static void main(String[] chars){
  47.  
  48. String un = "abccaba";
  49. String deux = "cabacaa";
  50. getLCS(un,deux);
  51.  
  52. String trois = "abcbdab";
  53. String quatre = "bdcaba";
  54. getLCS(trois,quatre);
  55.  
  56. String cinq = "stachu";
  57. String six = "shcu";
  58. getLCS(cinq,six);
  59.  
  60. String sept = "abcb";
  61. String huit = "bdacb";
  62. getLCS(sept,huit);
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement