mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 028.实现strStr,添加C#版本
This commit is contained in:
@ -1358,6 +1358,72 @@ impl Solution {
|
||||
}
|
||||
```
|
||||
|
||||
>前缀表统一不减一
|
||||
```C#
|
||||
public int StrStr(string haystack, string needle)
|
||||
{
|
||||
if (string.IsNullOrEmpty(needle))
|
||||
return 0;
|
||||
|
||||
if (needle.Length > haystack.Length || string.IsNullOrEmpty(haystack))
|
||||
return -1;
|
||||
|
||||
return KMP(haystack, needle);
|
||||
}
|
||||
|
||||
public int KMP(string haystack, string needle)
|
||||
{
|
||||
int[] next = GetNext(needle);
|
||||
int i = 0, j = 0;
|
||||
while (i < haystack.Length)
|
||||
{
|
||||
if (haystack[i] == needle[j])
|
||||
{
|
||||
i++;
|
||||
j++;
|
||||
}
|
||||
if (j == needle.Length)
|
||||
return i-j;
|
||||
else if (i < haystack.Length && haystack[i] != needle[j])
|
||||
if (j != 0)
|
||||
{
|
||||
j = next[j - 1];
|
||||
}
|
||||
else
|
||||
{
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int[] GetNext(string needle)
|
||||
{
|
||||
int[] next = new int[needle.Length];
|
||||
next[0] = 0;
|
||||
int i = 1, j = 0;
|
||||
while (i < needle.Length)
|
||||
{
|
||||
if (needle[i] == needle[j])
|
||||
{
|
||||
next[i++] = ++j;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (j == 0)
|
||||
{
|
||||
next[i++] = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
j = next[j - 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user