-
Notifications
You must be signed in to change notification settings - Fork 112
/
028-ImplementStrStr.cs
41 lines (38 loc) · 1.24 KB
/
028-ImplementStrStr.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//-----------------------------------------------------------------------------
// Runtime: 80ms
// Memory Usage: 20.6 MB
// Link: https://leetcode.com/submissions/detail/243054910/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _028_ImplementStrStr
{
public int StrStr(string haystack, string needle)
{
var needleLength = needle.Length;
if (needleLength == 0) { return 0; }
var loopLenght = haystack.Length - needleLength + 1;
var needleIndex = 0;
var n = 0;
for (int i = 0; i < loopLenght; i++)
{
needleIndex = n = 0;
while (needleIndex < needleLength
&& haystack[i + needleIndex] == needle[needleIndex])
{
if (n == 0 && needle[needleIndex] == needle[0])
{
n = needleIndex;
}
needleIndex++;
}
if (needleIndex == needleLength)
{
return i;
}
if (n > 0) i += n - 1;
}
return -1;
}
}
}