
Sponsored
Sponsored
The brute force approach involves iterating over each possible starting position of the needle in the haystack and checking if the substring from that position matches the needle.
Time Complexity: O((m-n+1)*n), where m is the length of haystack and n is the length of needle.
Space Complexity: O(1).
1def strStr(haystack: str, needle: str) -> int:
2 m, n = len(haystack), len(needle)
3 if n == 0:
4 return 0
5 for i in range(m - n + 1):
6 if haystack[i:i+n] == needle:
7 return i
8 return -1
9
10print(strStr("sadbutsad", "sad")) # Output: 0This Python solution uses slicing to compare parts of the haystack with the needle.
The KMP (Knuth-Morris-Pratt) algorithm is a more efficient string-searching algorithm. It preprocesses the needle to create a longest prefix-suffix (LPS) array, which is used to skip unnecessary comparisons while searching in the haystack.
Time Complexity: O(m + n), where m is the length of haystack and n is the length of needle.
Space Complexity: O(n), due to the LPS array.
1#include <vector>
using namespace std;
void computeLPSArray(string pat, int M, int* lps) {
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
int strStr(string txt, string pat) {
int N = txt.size();
int M = pat.size();
int lps[M];
computeLPSArray(pat, M, lps);
int i = 0;
int j = 0;
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
return i - j;
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return -1;
}
int main() {
cout << strStr("sadbutsad", "sad") << endl; // Output: 0
return 0;
}This C++ implementation follows the KMP algorithm for efficient string searching.