题目

实现 strStr() - 图1

解题思路

KMP算法:

https://www.bilibili.com/video/BV1jb411V78H?from=search&seid=16402901090638413249

代码

  1. class Solution {
  2. public int strStr(String haystack, String needle) {
  3. int n = haystack.length(), m = needle.length();
  4. if (m == 0) {
  5. return 0;
  6. }
  7. int[] pi = new int[m];
  8. for (int i = 1, j = 0; i < m; i++) {
  9. while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
  10. j = pi[j - 1];
  11. }
  12. if (needle.charAt(i) == needle.charAt(j)) {
  13. j++;
  14. }
  15. pi[i] = j;
  16. }
  17. for (int i = 0, j = 0; i < n; i++) {
  18. while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
  19. j = pi[j - 1];
  20. }
  21. if (haystack.charAt(i) == needle.charAt(j)) {
  22. j++;
  23. }
  24. if (j == m) {
  25. return i - m + 1;
  26. }
  27. }
  28. return -1;
  29. }
  30. }