Asked 1 year ago
0Comments
0 Views
Imagine you have two pieces of text: a long one called "haystack" and a short one called "needle".
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(); // Get the length of the larger string (haystack)
int m = needle.size(); // Get the length of the smaller string (needle)
// If needle is an empty string, return 0 (it is found at the beginning of haystack)
if (m == 0) return 0;
// Loop through the haystack up to the point where the remaining characters are less than needle's length
for (int i = 0; i <= n - m; i++) {
// Check if the substring of haystack starting from i matches the needle
for (int j = 0; j < m; j++) {
// If the characters don't match, break out of the inner loop
if (needle[j] != haystack[i + j]) {
break;
}
// If we have compared all characters of needle and they match, return the start index i
if (j == m - 1) {
return i;
}
}
}
// If we finish the loop without finding the needle, return -1
return -1;
}
};
Variables Setup:
n is the length of the haystack string.m is the length of the needle string.Edge Case:
needle is empty (m == 0), the function returns 0 because an empty string is considered to be at the start of any string.Main Loop:
i going from 0 to n - m. This ensures we do not start comparing past the point where needle can no longer fit in the remaining part of haystack.Inner Loop:
i in haystack, we check if the substring starting at i matches needle.j going from 0 to m - 1 to compare each character of needle with the corresponding character in haystack.Mismatch Check:
j the characters do not match (needle[j] != haystack[i + j]), we break out of the inner loop and move to the next position i.Full Match Check:
j == m - 1), it means needle is found in haystack starting at index i. We return i.Not Found:
needle is not found, we return -1.DRY RUN with an Example ! you can understand Better !
Share