Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
Method 1:
public int StrStr(string h, string n)
{
if (string.IsNullOrEmpty(n) || n == h) return 0;
if (n.Length > h.Length) return -1;
for (int i = 0; i < h.Length - n.Length + 1; ++i)
{
if (h[i] == n[0])
{
for (int j = 0; j < n.Length; j++)
{
if (h[i + j] != n[j]) break;
if (j == n.Length - 1) return i;
}
}
}
return -1;
}
Method 2:
public int StrStr(string h, string n) {
if(h == n) return 0;
else if(String.IsNullOrEmpty(h)) return -1;
else if(String.IsNullOrEmpty(n)) return 0;
for(int i = 0; i<h.Length;++i)
{
int j = 0;
while(j < n.Length && (i+j) < h. Length && h[i + j] == n[j])
{
j++;
}
if(j == n.Length)
{
return i;
}
}
return -1;
}