
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 <stdio.h>
2#include <string.h>
3
4int strStr(char * haystack, char * needle) {
5 int m = strlen(haystack);
6 int n = strlen(needle);
7 if (n == 0) return 0;
8 for (int i = 0; i <= m - n; i++) {
9 int j;
10 for (j = 0; j < n; j++) {
11 if (haystack[i + j] != needle[j])
12 break;
13 }
14 if (j == n) return i;
15 }
16 return -1;
17}
18
19int main() {
20 char *haystack = "sadbutsad";
21 char *needle = "sad";
22 printf("%d\n", strStr(haystack, needle)); // Output: 0
23 return 0;
24}This C code uses a naive approach to find the first occurrence of the needle in the haystack. It iterates over possible starting indices, checking if a matching substring can be found.
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 C solution uses the KMP algorithm, which preprocesses the needle to create an LPS array, reducing the number of comparisons required.