
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).
1public class Solution {
2 public int StrStr(string haystack, string needle) {
3 int m = haystack.Length;
4 int n = needle.Length;
5 if (n == 0) return 0;
6 for (int i = 0; i <= m - n; i++) {
7 int j = 0;
8 for (; j < n; j++) {
9 if (haystack[i + j] != needle[j])
10 break;
11 }
12 if (j == n) return i;
13 }
14 return -1;
15 }
16 public static void Main() {
17 Solution sol = new Solution();
18 Console.WriteLine(sol.StrStr("sadbutsad", "sad")); // Output: 0
19 }
20}This C# implementation uses nested loops to find the first occurrence of 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 public int StrStr(string haystack, string needle) {
int m = haystack.Length;
int n = needle.Length;
if (n == 0) return 0;
int[] lps = new int[n];
computeLPSArray(needle, n, lps);
int i = 0, j = 0;
while (i < m) {
if (haystack[i] == needle[j]) {
i++;
j++;
}
if (j == n) return i - j;
else if (i < m && haystack[i] != needle[j]) {
if (j != 0) j = lps[j - 1];
else i++;
}
}
return -1;
}
void computeLPSArray(string needle, int n, int[] lps) {
int length = 0;
lps[0] = 0;
int i = 1;
while (i < n) {
if (needle[i] == needle[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
public static void Main() {
Solution sol = new Solution();
Console.WriteLine(sol.StrStr("sadbutsad", "sad")); // Output: 0
}
}The C# solution uses the KMP algorithm and computes an LPS array to perform more efficient searches.