Mid From PDF Coding C# Coding Interview

Implement strStr() — Find first occurrence of a?

substring (needle) in a string (haystack)

int StrStr(string haystack, string needle)
{
if (needle == "") return 0;
int n = haystack.Length, m = needle.Length;
for (int i = 0; i <= n - m; i++)
{
int j;

Follow on:

for (j = 0; j < m; j++)
{
if (haystack[i + j] != needle[j])

break;

}
if (j == m) return i; // found
}
return -1;
}

Explanation:

Simple sliding window check each position; returns starting index or -1.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details