Skip to content

Commit 8af7bfc

Browse files
Create 28. 找出字符串中第一个匹配项的下标.md
1 parent dddbc1c commit 8af7bfc

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#### 28. 找出字符串中第一个匹配项的下标
2+
3+
难度:中等
4+
5+
---
6+
7+
给你两个字符串 `haystack``needle` ,请你在 `haystack` 字符串中找出 `needle` 字符串的第一个匹配项的下标(下标从 0 开始)。如果 `needle` 不是 `haystack` 的一部分,则返回  `-1`
8+
9+
**示例 1:**
10+
11+
```
12+
输入:haystack = "sadbutsad", needle = "sad"
13+
输出:0
14+
解释:"sad" 在下标 0 和 6 处匹配。
15+
第一个匹配项的下标是 0 ,所以返回 0 。
16+
```
17+
18+
**示例 2:**
19+
20+
```
21+
输入:haystack = "leetcode", needle = "leeto"
22+
输出:-1
23+
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
24+
```
25+
26+
**提示:**
27+
28+
* `1 <= haystack.length, needle.length <= 10^4`
29+
* `haystack``needle` 仅由小写英文字符组成
30+
31+
---
32+
33+
KMP 模板题:
34+
35+
```java
36+
class Solution {
37+
public int strStr(String haystack, String needle) {
38+
return kmp(haystack, needle);
39+
}
40+
41+
private int kmp(String haystack, String needle){
42+
int[] next = getNext(needle);
43+
int i = 0, j = 0;
44+
while(i < haystack.length() && j < needle.length()){
45+
if(j == -1 || haystack.charAt(i) == needle.charAt(j)){
46+
i++;
47+
j++;
48+
} else j = next[j];
49+
}
50+
if(j == needle.length()) return i - j;
51+
return -1;
52+
}
53+
54+
private int[] getNext(String needle){
55+
int[] next = new int[needle.length()];
56+
next[0] = -1;
57+
int j = 0, k = -1;
58+
while(j < needle.length() - 1){
59+
if(k == -1 || needle.charAt(j) == needle.charAt(k)){
60+
if(needle.charAt(++j) == needle.charAt(++k)) next[j] = next[k];
61+
else next[j] = k;
62+
} else k = next[k];
63+
}
64+
return next;
65+
}
66+
}
67+
```

0 commit comments

Comments
 (0)