Implement strStr()

LeetCode Q 28 - Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:
Input: haystack = "hello", needle = "ll" ; Output: 2

Example 2:
Input: haystack = "aaaaa", needle = "bba" ; Output: -1

Clarification:

  • What should we return when needle is an empty string? This is a great question to ask during an interview.
  • For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

Solution :

KMP algorithm: check is the suffix of a string is also a prefix of the string. In this case, once a mismatch happens, we can make use of the pre-matching.

table[i]: where to start matching in p after a mismatch at i + 1.

Code:

public int strStr(String haystack, String needle) {
	int len = haystack.length(), lenP = needle.length();
	if (lenP == 0) return 0;
	if (lenP > len) return -1;

	// build the table
	int i = 0, index = 1;
	while (index < lenP) {
		if (needle.charAt(index) == needle.charAt(i)) {
			table[index++] = ++i;
		} else {
			if (i != 0) {
				i = table[i - 1];
			} else {
				index++;
			}

		}
	}

	int maxLength = 0;
	for (int j = 0; j < len; ) {
		if (haystack.charAt(j) == needle.charAt(maxLength)) {
			j++; maxLength++;
			if (maxLength == lenP) return j - maxLength;
		} else {
			if (maxLength > 0)
				maxLength = table[maxLength - 1];
			else
				j++;
		}
	}

	return -1;
}

   Reprint policy


《Implement strStr()》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC