Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package leetcode;
- public class KMP {
- private int[] getNext(String needle){
- int[] next = new int[needle.length()];
- int j = 0;
- next[0] = 0;
- for (int i = 1; i < next.length; i++) {
- while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
- j = next[j - 1];
- }
- // next represent when match failed, this means needle[j] != text[i], and also means j - 1 elements equal
- // next[i] store the biggest equivalent prefix of needle[i]
- if (needle.charAt(i) == needle.charAt(j)) {
- // j point to the character to match in needle
- j++;
- }
- next[i] = j;
- }
- return next;
- }
- public int strStr(String haystack, String needle) {
- int[] next = getNext(needle);
- int j = 0;
- for (int i = 0; i < haystack.length(); i++) {
- while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
- j = next[j - 1];
- }
- if (haystack.charAt(i) == needle.charAt(j)) {
- j++;
- }
- if (j == needle.length()) {
- // when the last character(needle[needle.length() - 1]) has matched, j++, now j equals to needle.length()
- return i - j + 1;
- }
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment