
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).
1#include <iostream>
2using namespace std;
3int strStr(string haystack, string needle) {
4 int m = haystack.size();
5 int n = needle.size();
6 if (n == 0) return 0;
7 for (int i = 0; i <= m - n; i++) {
8 int j = 0;
9 for (j = 0; j < n; j++) {
10 if (haystack[i + j] != needle[j])
11 break;
12 }
13 if (j == n) return i;
14 }
15 return -1;
16}
17
18int main() {
19 cout << strStr("sadbutsad", "sad") << endl; // Output: 0
20 return 0;
21}This C++ solution uses a similar approach as the C solution, iterating over the haystack to match 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
This JavaScript implementation efficiently searches for the needle using the KMP algorithm with an LPS array.