Input: haystack = "hello", needle = "ll"
Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1
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;
}
}
class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) {
return 0;
}
int i = 0;
while (i < haystack.length()) {
if (haystack.length() - i < needle.length()) {
break;
}
if (haystack.charAt(i) == needle.charAt(0)) {
int j = i;
while (j - i < needle.length() && haystack.charAt(j) == needle.charAt(j - i)) {
++j;
}
if (j - i == needle.length()) {
return i;
}
}
++i;
}
return -1;
}
}
3. Time & Space Complexity