28 Implement strStr()
1. Question
Input: haystack = "hello", needle = "ll"
Output: 2Input: haystack = "aaaaa", needle = "bba"
Output: -12. Implementation
class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) {
return 0;
}
if (haystack.length() < needle.length()) {
return -1;
}
// KMP Algorithm
int[] next = getNextArray(needle);
int i = 0, j = 0;
while (i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
++i;
++j;
}
else if (j != 0) {
j = next[j - 1];
}
else {
++i;
}
}
if (j == needle.length()) {
return i - needle.length();
}
return -1;
}
public int[] getNextArray(String pattern) {
int[] next = new int[pattern.length()];
int index = 0;
for (int i = 1; i < pattern.length(); ) {
if (pattern.charAt(i) == pattern.charAt(index)) {
next[i] = index + 1;
++index;
++i;
}
else if (index != 0) {
index = next[index - 1];
}
else {
next[index] = 0;
++i;
}
}
return next;
}
}3. Time & Space Complexity
Last updated