Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5594341

Browse files
committed
Update 028.实现strStr,添加C#版本
1 parent 83efa79 commit 5594341

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

‎problems/0028.实现strStr.md‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,6 +1358,72 @@ impl Solution {
13581358
}
13591359
```
13601360

1361+
>前缀表统一不减一
1362+
```C#
1363+
public int StrStr(string haystack, string needle)
1364+
{
1365+
if (string.IsNullOrEmpty(needle))
1366+
return 0;
1367+
1368+
if (needle.Length > haystack.Length || string.IsNullOrEmpty(haystack))
1369+
return -1;
1370+
1371+
return KMP(haystack, needle);
1372+
}
1373+
1374+
public int KMP(string haystack, string needle)
1375+
{
1376+
int[] next = GetNext(needle);
1377+
int i = 0, j = 0;
1378+
while (i < haystack.Length)
1379+
{
1380+
if (haystack[i] == needle[j])
1381+
{
1382+
i++;
1383+
j++;
1384+
}
1385+
if (j == needle.Length)
1386+
return i-j;
1387+
else if (i < haystack.Length && haystack[i] != needle[j])
1388+
if (j != 0)
1389+
{
1390+
j = next[j - 1];
1391+
}
1392+
else
1393+
{
1394+
i++;
1395+
}
1396+
}
1397+
return -1;
1398+
}
1399+
1400+
public int[] GetNext(string needle)
1401+
{
1402+
int[] next = new int[needle.Length];
1403+
next[0] = 0;
1404+
int i = 1, j = 0;
1405+
while (i < needle.Length)
1406+
{
1407+
if (needle[i] == needle[j])
1408+
{
1409+
next[i++] = ++j;
1410+
}
1411+
else
1412+
{
1413+
if (j == 0)
1414+
{
1415+
next[i++] = 0;
1416+
}
1417+
else
1418+
{
1419+
j = next[j - 1];
1420+
}
1421+
}
1422+
}
1423+
return next;
1424+
}
1425+
```
1426+
13611427
<p align="center">
13621428
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
13631429
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /