Problem
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
*Explanation: *"sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
*Explanation: *"leeto" did not occur in "leetcode", so we return -1.
Code:
Iteration 1: (Poor) - Tried without built in functions
public int StrStr(string haystack, string needle) {
if (haystack.Length < needle.Length) return -1;
for (var i = 0; i < haystack.Length; i++)
{
if (haystack[i..].StartsWith(needle)) return i;
}
return -1;
}
Why is this bad?
Well, there's unnecessary allocation of strings. haystack[i..]
creates a new string on every iteration, which is costly for large strings.
Should handle empty needle (LeetCode requires returning 0).
Should handle empty haystack gracefully.
In C# it's just unnecessary
Iteration 2: (More Efficient)
public int StrStr(string haystack, string needle) {
return haystack.IndexOf(needle, StringComparison.Ordinal);
}
Approach
Bosh, simply use C#'s built in IndexOf
method, which will return the index of one character / string in another. If it doesn't exist it will return -1 (not found)
Top comments (0)