progppy

KMP

Nov 5th, 2025
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | Source Code | 0 0
  1. package leetcode;
  2.  
  3. public class KMP {
  4.     private int[] getNext(String needle){
  5.         int[] next =  new int[needle.length()];
  6.         int j = 0;
  7.         next[0] = 0;
  8.         for (int i = 1; i < next.length; i++) {
  9.             while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
  10.                 j = next[j - 1];
  11.             }
  12.             // next represent when match failed, this means needle[j] != text[i], and also means j - 1 elements equal
  13.             // next[i] store the biggest equivalent prefix of needle[i]
  14.             if (needle.charAt(i) == needle.charAt(j)) {
  15.                 // j point to the character to match in needle
  16.                 j++;
  17.             }
  18.             next[i] = j;
  19.         }
  20.         return next;
  21.     }
  22.     public int strStr(String haystack, String needle) {
  23.         int[] next = getNext(needle);
  24.         int j = 0;
  25.         for (int i = 0; i < haystack.length(); i++) {
  26.             while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
  27.                 j = next[j - 1];
  28.             }
  29.             if (haystack.charAt(i) == needle.charAt(j)) {
  30.                 j++;
  31.             }
  32.             if (j == needle.length()) {
  33.                 // when the last character(needle[needle.length() - 1]) has matched, j++, now j equals to needle.length()
  34.                 return i - j + 1;
  35.             }
  36.  
  37.         }
  38.         return -1;
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment