题目

类型:字符串
image.png

解题思路

Knuth-Morris-Pratt 算法

使用 Knuth-Morris-Pratt 算法来实现字符串匹配的功能。
在应用 Knuth-Morris-Pratt 算法时,被匹配字符串是循环叠加的字符串,所以下标要进行取余操作,并且匹配终止的条件为 b 开始匹配的位置超过第一个叠加的 a

代码

  1. class Solution {
  2. public int repeatedStringMatch(String a, String b) {
  3. int an = a.length(), bn = b.length();
  4. int index = strStr(a, b);
  5. if (index == -1) {
  6. return -1;
  7. }
  8. if (an - index >= bn) {
  9. return 1;
  10. }
  11. return (bn + index - an - 1) / an + 2;
  12. }
  13. public int strStr(String haystack, String needle) {
  14. int n = haystack.length(), m = needle.length();
  15. if (m == 0) {
  16. return 0;
  17. }
  18. int[] pi = new int[m];
  19. for (int i = 1, j = 0; i < m; i++) {
  20. while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
  21. j = pi[j - 1];
  22. }
  23. if (needle.charAt(i) == needle.charAt(j)) {
  24. j++;
  25. }
  26. pi[i] = j;
  27. }
  28. for (int i = 0, j = 0; i - j < n; i++) { // b 开始匹配的位置是否超过第一个叠加的 a
  29. while (j > 0 && haystack.charAt(i % n) != needle.charAt(j)) { // haystack 是循环叠加的字符串,所以取 i % n
  30. j = pi[j - 1];
  31. }
  32. if (haystack.charAt(i % n) == needle.charAt(j)) {
  33. j++;
  34. }
  35. if (j == m) {
  36. return i - m + 1;
  37. }
  38. }
  39. return -1;
  40. }
  41. }