题目链接
    image.png
    image.png
    image.png

    1. class Solution {
    2. public int strStr(String haystack, String needle) {
    3. int len = haystack.length();
    4. int[] next = getNext(needle);
    5. int j = -1; // 表示的是需要字符串搜索的下标
    6. for(int i = 0; i < len; i++) {
    7. while(j>=0 && haystack.charAt(i) != needle.charAt(j+1)) {
    8. j = next[j];
    9. }
    10. if(haystack.charAt(i) == needle.charAt(j+1)) {
    11. j++;
    12. }
    13. if(j+1 == needle.length()) {
    14. return i-needle.length()+1;
    15. }
    16. }
    17. return -1;
    18. }
    19. public int[] getNext(String needle) {
    20. // 构建next数组
    21. int len = needle.length();
    22. int[] next = new int[len];
    23. int j = -1; // 使用-1表示对应下标的前缀匹配长度
    24. next[0] = j;
    25. for(int i = 1; i < len; i++) {
    26. // 需要j是大于-1才能进行查找前后缀匹配的长度
    27. while(j >= 0 && needle.charAt(i) != needle.charAt(j+1)) {
    28. // 找到匹配不到或者匹配到为止
    29. j = next[j];
    30. }
    31. // j+1是因为会为-1
    32. if(needle.charAt(j+1) == needle.charAt(i)) {
    33. j++; // 说明当前j下表2和对应的i下标值相等
    34. }
    35. next[i] = j;
    36. }
    37. return next;
    38. }
    39. }