Guest User

Untitled

a guest
Jun 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. String stringOne;
  7. String stringTwo;
  8.  
  9. if (args.length > 2) {
  10. stringOne = args[0];
  11. stringTwo = args[1];
  12. } else {
  13. stringOne = "мама мыла раму";
  14. stringTwo = "саша мыл раму";
  15. }
  16.  
  17. List<String> longestCommonSubstrings = getLongestCommonSubstrings(stringOne, stringTwo);
  18.  
  19. StringBuilder result = new StringBuilder();
  20. if (longestCommonSubstrings == null || longestCommonSubstrings.size() == 0) {
  21. result.append("Общих подстрок не найдено.");
  22. } else if (longestCommonSubstrings.size() == 1) {
  23. result.append("Найдена одна наибольшая общая подстрока: ");
  24. } else {
  25. int size = longestCommonSubstrings.size();
  26. result.append("Всего найдено ")
  27. .append(size)
  28. .append(" различных подстрок наибольшей длины длины: ");
  29. }
  30.  
  31. if (longestCommonSubstrings != null) {
  32. for (String lcs : longestCommonSubstrings) {
  33. result.append('\n');
  34. result.append(lcs);
  35. }
  36. }
  37.  
  38. System.out.println(result.toString());
  39. }
  40.  
  41. private static List<String> getLongestCommonSubstrings(String stringOne, String stringTwo) {
  42. int stringOneLength = stringOne.length();
  43. int stringTwoLength = stringTwo.length();
  44. int matchTable[][] = new int[stringOneLength][stringTwoLength];
  45.  
  46. List<String> result = null;
  47.  
  48. int maxLength = Integer.MIN_VALUE;
  49.  
  50. for (int i = 0; i < stringOneLength; i++) {
  51. for (int j = 0; j < stringTwoLength; j++) {
  52. if (stringOne.charAt(i) == stringTwo.charAt(j)) {
  53. if (i == 0 || j == 0) matchTable[i][j] = 1;
  54. else matchTable[i][j] = matchTable[i - 1][j - 1] + 1;
  55.  
  56. if (matchTable[i][j] > maxLength) {
  57. maxLength = matchTable[i][j];
  58. result = new ArrayList<>();
  59. result.add(stringOne.substring(i - maxLength + 1, i + 1));
  60. } else if (matchTable[i][j] == maxLength) {
  61. result.add(stringOne.substring(i - maxLength + 1, i + 1));
  62. }
  63. } else {
  64. matchTable[i][j] = 0;
  65. }
  66. }
  67. }
  68.  
  69. return result;
  70. }
  71. }
Add Comment
Please, Sign In to add comment